2012-12-29 108 views
1

我想在表單中輸入姓名和電話,並根據輸入值從mysql獲取數據。當我通過單擊功能運行查詢時,瀏覽器顯示我的php和查詢,但不是來自數據庫的值,而是顯示'object HTMLInputElement'。ajax檢索mysql數據

我必須在我的腳本中丟失一些東西,但無法弄清楚它是什麼。 有人可以告訴我,當我提交這個ajax/mysql爲什麼值沒有被顯示。請參見下面的代碼和漢克斯您的幫助...

HTML和腳本

<script type="text/javascript" src="jquery-1.8.3.min.js"></script> 
<script language="javascript" type="text/javascript"> 

function ajaxFunction(){ 
var ajaxRequest; 

try{ 

    ajaxRequest = new XMLHttpRequest(); 
} catch (e){ 

    try{ 
     ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); 
    } catch (e) { 
     try{ 
      ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
     } catch (e){ 

      alert("Your browser broke!"); 
      return false; 
     } 
    } 
} 

ajaxRequest.onreadystatechange = function(){ 
    if(ajaxRequest.readyState == 4){ 
     var ajaxDisplay = document.getElementById('ajaxDiv'); 
     ajaxDisplay.innerHTML = ajaxRequest.responseText; 
    } 
} 
var age = document.getElementById('lname').value; 
var queryString = "?lname=" + lname + "&phone=" + phone ; 
ajaxRequest.open("GET", "find.php" + queryString, true); 
ajaxRequest.send(null); 
} 

</script> 
<form name='myForm'> 
Last Name: <input type='text' id='lname' /> 
Phone: <input type='text' id='phone' /> 
<input type='button' onclick='ajaxFunction()' value='Query MySQL' /> 
</form> 
<div id='ajaxDiv'>Your result will display here</div> 
</body> 
</html> 

PHP

$inputedname = $_GET['lname']; 
$inputedphone = $_GET['phone']; 

$inputedname = mysql_real_escape_string($inputedname); 
$inputedphone = mysql_real_escape_string($inputedphone); 

$query = "SELECT FirstName, Phone FROM ClientInfo WHERE LastName = '$inputedname' AND Phone = '$inputedphone'"; 

$qry_result = mysql_query($query) or die(mysql_error()); 


$display_string = "<table>"; 
$display_string .= "<tr>"; 
$display_string .= "<th>Name</th>"; 
$display_string .= "<th>Phone</th>"; 
$display_string .= "</tr>"; 


while($row = mysql_fetch_array($qry_result)){ 
$display_string .= "<tr>"; 
$display_string .= "<td>$row[FirstName]</td>"; 
$display_string .= "<td>$row[Phone]</td>"; 
$display_string .= "</tr>"; 

} 
echo "Query: " . $query . "<br />"; 
$display_string .= "</table>"; 
echo $display_string; 

在瀏覽器

enter image description here

回答

1

那是因爲你從來沒有定義變量lnamephone在你的var queryString = "?lname=" + lname + "&phone=" + phone ;一行。因此,瀏覽器會根據您的輸入元素ID生成變量。在字符串連接中使用DOM元素時,將調用其toString(),並輸出[object HTMLInputElement]。這是IE早期給我們的功能,其他瀏覽器複製爲IE兼容。這是一個你不應該使用的功能。

以下代碼將解決您的問題。

var lname = document.getElementById('lname').value; 
var phone = document.getElementById('phone').value; 
var queryString = "?lname=" + lname + "&phone=" + phone ; 
ajaxRequest.open("GET", "find.php" + queryString, true); 

截至順便說一句,以防止SQL注入,你應該使用prepared statements代替http://php.net/manual/en/function.mysql-real-escape-string.php它被廢棄

+0

這是它。我會研究準備好的陳述。感謝您的幫助! – user1933115