2

$ // 首先,我发送执行 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 中获取值以显示在文本框中$

4

1 回答 1

1

In your php code, you should better encode response to JSON:

data1=array($get_row1[0],
        $get_row1[1],
        $get_row1[2],
        $get_row1[3]);

json_encode($data1); 

And then, in JS code, you can parse response string using 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
        }
    }

}

Note: JSON.parse is available in modern browsers only. In IE7, for instance, you will get an error because of that. To fix this problem you can download this small piece of JavaScript.

For jQuery solution take a look here

于 2013-07-05T09:31:01.923 回答