如何在多个变量中分离ajax响应以及如何调用它们

how to separate ajax response in multiple variables and how to call them?

本文关键字:何调用 调用 ajax 变量 分离 响应      更新时间:2023-09-26

我正在使用ajax从数据库中获取数据,并将其显示在文本框中。如果您只想在一个文本框中显示ajax响应,那么到目前为止,我在网上看到的示例都是有效的。如果我们想从ajaxresponse中获取php的多个变量,并将其存储在请求页面的多个文本框中,我们如何将其分离。以下是示例:

第1页(AJAX请求)

HTML代码:

<div class="control-group">
    <label class="control-label" for="focusedInput" id="label">Student ID :</label>
    <div class="controls">
        <input class="input-xlarge focused" id="std_id" type="text" placeholder="Student ID" name="std_id"  onKeyUp="get_student();" required>
    </div>
</div>
<div class="control-group">
    <label class="control-label" for="focusedInput" id="label">Student Name:</label>
    <div class="controls">
        <input class="input-xlarge focused" id="std_name" type="text" placeholder="Student Name" name="std_name" readonly>
    </div>
</div>
<div class="control-group">
    <label class="control-label" for="focusedInput" id="label">Semester :</label>
    <div class="controls">
        <input class="input-xlarge focused" id="semester" type="text" placeholder="Semester" name="semester" readonly>
    </div>
</div>
<div class="control-group">
    <label class="control-label" for="focusedInput" id="label">Room #:</label>
    <div class="controls">
        <input class="input-xlarge focused" id="r_num" type="text" placeholder="Room Number" name="r_num" readonly>
    </div>
</div>

JAVASCRIPT&AJAX请求代码:

<script type="text/javascript">
    function get_student()
    {
        var std_id=document.getElementById("std_id").value;
        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)  
            {
                document.getElementById("std_name").value=xmlhttp.responseText;
            }
        };
        xmlhttp.open("GET","AjaxResponse.php?std_id="+std_id+",true);
        xmlhttp.send();
    }
</script>

第2页(AJAX响应):

<?php
    $std_id=$_GET['std_id'];
    $select_std_dtls=mysql_query("SELECT tbl_student_module.std_name,tbl_room_allotment_module.r_num,MAX(tbl_fee_module.semester) AS SEM FROM tbl_room_allotment_module INNER JOIN tbl_student_module ON tbl_room_allotment_module.std_id=tbl_student_module.std_id INNER JOIN tbl_fee_module ON tbl_student_module.std_id=tbl_student_module.std_id WHERE tbl_room_allotment_module.std_id=".$std_id." AND tbl_fee_module.std_id=".$std_id." AND tbl_room_allotment_module.a_status='active'")or die(mysql_error($select_std_dtls));
    if($row=mysql_fetch_array($select_std_dtls))
    {
        $db_std_name=$row['std_name'];
        $db_r_num=$row['r_num'];
        $db_semester=$row['SEM']+1;
    }
    echo $db_std_name,$db_r_num,$db_semester;
?>

在这里,您可以看到ajax响应将显示在Student Name文本字段中,但我想将所有ajax响应分开,并将它们显示在单独的字段中。请帮忙。提前谢谢。

按照您的要求,我会做两个更改。

第一个是对从PHP页面返回的响应进行定界。这意味着您可以用任意字符(如逗号、波浪号或管道)分隔数据的不同部分,这是我最喜欢的字符之一。你可以这样做:

echo "$db_std_name|$db_r_num|$db_semester"

然后,在您的AJAX处理程序中,您可以随心所欲地将数据分离。代替:

document.getElementById("std_name").value=xmlhttp.responseText;

您将首先通过分隔符将数据拆分为多个部分,然后适当地分配它:

var parts = xmlhttp.responseText.split('|')
document.getElementById("std_name").value = parts[0]
document.getElementById("r_num").value = parts[1]
document.getElementById("semester").value = parts[2]

或者类似的东西。如果数据是要读取而不是编辑的,我可能会将其分配给标签。

一个快速的答案是将php页面上的结果数组编码为json

`echo encode_json($row);`

然后,您将可以访问作为json对象的结果,该对象具有键值对

我认为最简单的解决方案是基于JSON的响应。如果你想这样做,你必须改变你的PHP如下:

<?php
$std_id=$_GET['std_id'];
$sql = <<<HERE_ENDS_SQL
SELECT tbl_student_module.std_name,tbl_room_allotment_module.r_num,MAX(tbl_fee_module.semester) AS SEM
  FROM tbl_room_allotment_module
 INNER JOIN tbl_student_module ON tbl_room_allotment_module.std_id=tbl_student_module.std_id
 INNER JOIN tbl_fee_module ON tbl_student_module.std_id=tbl_student_module.std_id
 WHERE tbl_room_allotment_module.std_id=$std_id
   AND tbl_fee_module.std_id=$std_id
   AND tbl_room_allotment_module.a_status='active'
HERE_ENDS_SQL;
$select_std_dtls = mysql_query($sql) or die(mysql_error($select_std_dtls));
$result = '{}';
if($row=mysql_fetch_array($select_std_dtls))
{
    $result = json_encode([
        'std_name' => $row['std_name'],
        'r_num' => $row['r_num'],
        'semester' => $row['SEM'] + 1,
    ]);
}
echo $result;

之后,您必须更改ajax的回调函数,如下所示:

function () {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var jsonObj = JSON.parse(xmlhttp.responseText);
        document.getElementById("std_name").value=jsonObj.std_name;
        document.getElementById("r_num").value=jsonObj.r_num;
        document.getElementById("semester").value=jsonObj.semester;
    }
};

这应该对你有用。但是您仍然有一些SQL注入,它仍然不是最佳实践,但它是有效的。

我建议用json格式将响应发送到ajax url(AjaxResponse.php?std_id=x)。看见http://www.json.org

这允许您分离变量,例如使用数组:

[
 { "name":"John" , "semester":"2" }, 
 { "name":"Anna" , "semester":"3" }
]

然后,在浏览器中,您可以将此json格式解析为javascript数组:

var obj = JSON.parse(json);

将结果放入php文件中的数组中,并使用json_encode返回HTML。

例如:

      echo json_encode($result_array);

并在javascript:中使用以下函数

  • JSON.stringify
  • JSON.parse

    student_record = JSON.parse(msg);