【问题标题】:How to display the data fetched from the database in the form如何在表单中显示从数据库中获取的数据
【发布时间】:2013-07-05 17:34:20
【问题描述】:

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

【问题讨论】:

  • 我可以看到你在 for 循环中使用 $ 假设它的别名为 jQuery 为什么不使用 $.ajax()
  • 什么是tmp数组?你提到了 temp,但你也有 tmp。
  • 您在问如何正确解析来自 ajax 的响应?也就是说,如何将其转换为 JS-array?
  • 一般来说js代码对php页面进行请求,通过id获取打印出来的数据。你想要这个数据在一个 js 数组中吗?
  • @2-Stroker 真的我更喜欢 jQuery 而不是“普通”的 ajax!

标签: php javascript ajax


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2018-04-11
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多