2015-11-19 125 views
1

好吧,我是新來的Ajax。我的問題是我不確定如何檢索<input>標記中的數據並將其發送到Ajax。我試圖在互聯網上搜索,但大多數解決方案都使用jQuery Ajax,這是我目前沒有在尋找的。如何將輸入值傳遞給ajax

這是我的代碼。

我要保存這個值,這樣我的Ajax可以讀取它...

<input id="IDValue" name="IDValue" value="<?php echo $row['exist']?>" > 

這是我的Ajax腳本...

function message(){ 
    var ID=$(".IDValue").val(); 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function(){ 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
          } 
         }; 
      xmlhttp.open("POST","retrieveMsg.php?q=" +ID,true); 
      xmlhttp.send(); 
       } 

請幫幫我,夥計們。我做這個方法的原因是(我以前的帖子)Send input value to php using ajax with result printed to div

+1

好吧,不過你要使用jQuery來獲得輸入字段值。你正在把它放在面前,但你需要一個散列。 (var ID = $(「#IDValue」)。val();) – KiwiJuicer

+1

'var ID = document.querySelector('#IDValue')。value;'是非jquery的等價物。 – Shilly

+1

查看https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files。 –

回答

3

更換它

var ID=$(".IDValue").val(); 

隨着

var ID = document.getElementById("IDValie").value; 
+0

謝謝!但是如果它是'」>'(如果是class?) – topacoBoy

+1

.getElementsByClassName( 'IDValue'); – kannan

+0

它有助於你解決問題嗎? – kannan

0

我感到困惑的$行[「存在」]返回值或者不是,以及用於id =「txtHint」的html控件。在這裏,我提供的演示其同某種方式對你的代碼...嘗試和有一個想法,並進行更改按您的要求......

<html> 
    <head> 
    <script src="jquery.js"></script> 
    </head> 
    <body> 
     <input id="IDValue" name="IDValue" value="<?php echo 'hello';?>" > 
     <textarea id="txtHint"></textarea> 
     <input type="button" value="Click" onClick="message()"/> 
    <script> 
     function message(){ 
    var ID=$("#IDValue").val(); 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function(){ 
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
      document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
          } 
         }; 
      xmlhttp.open("POST","login.php?q=" +ID,true); 
      xmlhttp.send(); 
       } 
    </script> 
    </body> 
</html>