显示两个PHP变量切换jQuery Ajax的更好方法

Hzy*_*zyf 1 javascript php ajax jquery

我从表中得到两个随机值.值位于同一行.

<?php
    $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
    $row = mysql_fetch_array($result);
    echo $row["name"];
    echo $row["surname"];
?>
Run Code Online (Sandbox Code Playgroud)

我想通过使用jQuery Ajax函数在HTML页面的不同div上显示这两个值.

$(function()
{
    $("#sentence-form").submit(function()
    {
        $.ajax(
        {
            type: "GET",
            url: "newperson.php",
            success: function(response)
            {
                $("#top-container").append(response);  /* Both name and surname  */
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

问题是将两个值分开以在div中显示不同的值.我尝试使用两个Ajax调用,并将布尔数据发送给PHP以与if语句一起使用.因此,其中一个Ajax调用显示名称,另一个显示姓氏.但由于随机化,找到姓氏的姓氏有点复杂.

什么是更好的方法?

lon*_*day 8

是的:以数据结构发送数据 - 可能是JSON - 因此您的客户端代码知道哪个位是哪个.

首先,使用PHP的json_encode函数发送数据:

echo json_encode(array(
    'name' => $row['name'],
    'surname' => $row['surname']
));
Run Code Online (Sandbox Code Playgroud)

然后使用浏览器解析JSON的能力:

$.ajax({
    type: "GET",
    url: "newperson.php",
    dataType: 'json',
    success: function (response) {
        $("#name-container").append(response.name);
        $("#surname-container").append(response.surname);
    }
});
Run Code Online (Sandbox Code Playgroud)

response现在是一个Javascript对象(类似于{name: 'John', surname: 'Smith'}),因此您可以将这两个部分作为普通对象成员进行访问.