2012-12-29 61 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