$ //首先我发送执行sql查询的php代码,此代码执行查询以从数据库获取数据并将所有内容存储在get_row1中并将其作为响应发送给ajax $
<?php
$connect = mysql_connect("localhost", "root", "");
$data = mysql_select_db("testme", $connect);
$identity = $_REQUEST['id'];
$query = "SELECT * FROM student_demo WHERE id=1";
$getdata = mysql_query($query);
$get_row1 = mysql_fetch_array($getdata);
$data1 = array(
$get_row1[0],
$get_row1[1],
$get_row1[2],
$get_row1[3]
);
print_r($data1);
?>
$ //这会将$ data1发送回ajax代码$
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
temp1 = xmlhttp.responseText.split("=>");
alert(temp1);
for (var i = 0; i < 10; i++) {
$('.data' + i).val(tmp1[i]);
if (tmp[i] == "[0]") {
document.getelementById("c_name").value = temp1[i];
}
}
}
}
xmlhttp.open("GET", "process.php?id=" + ID, true);
xmlhttp.send();
现在应该做些什么来使数组temp1中的值显示在文本框$
中答案 0 :(得分:1)
在您的PHP代码中,您应该更好地编码对JSON的响应:
data1=array($get_row1[0],
$get_row1[1],
$get_row1[2],
$get_row1[3]);
json_encode($data1);
然后,在JS代码中,您可以使用JSON.parse
解析响应字符串:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
temp1=JSON.parse(xmlhttp.responseText);
console.log(temp1); // this way you can see exact structure of an object in browser console
var i;
for(i=0;i<10;i++)
{
$('.data'+i).val(tmp1[i]); // not sure what is that. If you are already using jQuery, then you can do everything even simpler
if(tmp[i]=="[0]")
{
document.getElementById("c_name").value=temp1[i]; // see here getElementById - javascript is case sensitive
}
}
}
注意:JSON.parse
仅适用于现代浏览器。例如,在IE7中,由于这个原因,您将收到错误。要解决此问题,您可以下载this一小段JavaScript。
对于jQuery解决方案,请查看here