gpt4 book ai didi

html - ajax获取mysql数据

转载 作者:行者123 更新时间:2023-11-29 00:36:25 24 4
gpt4 key购买 nike

我正在尝试在表单中输入姓名和电话,并根据输入值从 mysql 获取数据。当我通过单击功能运行查询时,浏览器显示我的 php 和查询,但它显示的不是数据库中的值,而是“对象 HTMLInputElement”。

我一定是在我的脚本中遗漏了一些东西,但无法弄清楚它是什么。当我提交此 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

最佳答案

那是因为您从未在 var queryString = "?lname="+ lname + "&phone="+ phone 中定义变量 lnamephone 行。因此,浏览器会根据您的输入元素 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 注入(inject),你应该使用 prepared statements而不是 http://php.net/manual/en/function.mysql-real-escape-string.php已弃用

关于html - ajax获取mysql数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14085497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com