如何在 AJAX 请求中显示 PHP 返回的 JSON 数组


how to display the json array returned by php in an ajax request

我的 Ajax 请求看起来像这样

  $.ajax({
         type: "POST",
        url: "new1.php",
       dataType: "json",
        data: { name: $('#name-typed').val()},
        success: function(response) {
        $('.cartcontainer').append(' <div class="cartproduct"><img src="images/deletesm.png" height="18" width="18" alt="deleteproduct" id="delete" data-toggle="tooltip" data-placement="bottom" title="Delete Product"/><span class="cartlist"><span><img src="images/wheatthumbnail.png" alt="ricethumbnail" class="cartcontent thmbnail" /></span><ul class="cartcontent"><li class="col"> </li><li class="col">'+ response.id + '</li><li class="crtqtymanuplator"><button>-</button><input type="text" id="crtcountholder" /><button>+</button></li></ul></span></div> ')
    }
  });

我的 PHP 文件看起来很新1.php看起来像这样

<?php

$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password,"mydb");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "SELECT id FROM names";
$result = $conn->query($sql);
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
    $jsonData['id'] = $array;
}
echo json_encode($jsonData);
else {
    echo "0 results";
}
$conn->close();
?>

我想要的是将返回id显示为数组json。怎么办?

使用 $jsonData['id'][] = $array; 而不是 $jsonData['id'] = $array;

此外,当您期望 JSON 输出时,还要避免打印额外的内容,例如"0 结果"。

您向服务器发送 varibale $_POST['name'],我假设您必须收到一个具有此名称的 Id...在 new1 中尝试此代码.php

$name = $_POST['name'];
$sql = "SELECT id FROM names WHERE `name` = ? LIMIT 1";
$stmt  = $conn->prepare($sql);
$stmt->bind_param("s", $name);
$stmt->execute();
$result = $stmt->get_result();
while ($array = $result->fetch_assoc()) {
    $jsonData = $array;
}
echo json_encode($jsonData);
$conn->close();
?>

有几件事需要处理:

1. 将内容类型声明为 JSON

在回显 JSON 之前,在我们的 PHP 代码中添加以下行:

header("Content-Type: application/json");

2. 不要输出除 JSON 以外的任何内容

此代码都无效,因为与内容类型冲突:

else {
    echo "0 results";
}

您没有与此else块匹配的if,但也许您试图简化该问题的代码,但没有看到它变得无效。

无论如何,完全删除此块。如果您有if测试与此else匹配的行数,请将其也删除。

JSON 输出就足够了。

3. 输出的不仅仅是最后一个 ID

您的查询返回一个 ID 列表,但您当前只保留最后一个 ID。因此,请更改该代码:

$jsonData = array('id' => array());
while ($array = mysql_fetch_row($result)) {
    $jsonData['id'][] = $array;
}

或者,如果您确实打算只获取一个特定 ID,则更改您的 SQL 语句,使其仅检索特定用户的 ID。 @Aleksandr在他的回答中很好地发现了这一点,所以我不会在这里重复。把功劳归于他。

尽管如此,即使您将 SQL 更改为仅返回 1 条记录,上述更改和建议仍然有效。

4. 使用模板 HTML 而不是长 HTML 字符串

回调中的 HTML 字符串很长且难以阅读。在 HTML 中使用模板标记,将 HTML 插入不可见的div 中,如下所示:

<div id="template1" style="display:none">
    <div class="cartproduct">
        <img src="images/deletesm.png" height="18" width="18"
             alt="deleteproduct" id="delete" data-toggle="tooltip" 
             data-placement="bottom" title="Delete Product"/>
        <span class="cartlist">
            <span>
                <img src="images/wheatthumbnail.png" alt="ricethumbnail"
                     class="cartcontent thmbnail" />
            </span>
            <ul class="cartcontent">
                <li class="col"></li>
                <li class="col">$1</li>
                <li class="crtqtymanuplator">
                    <button>-</button>
                    <input type="text" id="crtcountholder" />
                    <button>+</button>
                </li>
            </ul>
        </span>
    </div>
</div>

上面的 HTML 有 $1 来标识应该在何处注入 ID。然后你的 JavaScript 将检索该不可见模板元素的innerHTML,注入 ID 并附加它。请参阅下一点下的代码。

4. 处理多个 ID

在 JavaScript 代码中,您目前只处理一个 ID。与上述更改一样,响应将是一个数组,像这样更改 JavaScript 成功回调,使用模板 HTML。

请注意,如果 ID 可以包含任何字符,则应确保对其进行转义。但如果 ID 是数字,则不需要此步骤:

success: function(response) {
    if (response.id !== undefined) {
        response.id.forEach(function (id) {
            // Escape id for use in HTML (Not needed if ID is numerical)
            id = $('<div/>').text(id).html();
            // Get template HTML, and inject id
            var html = $('#template1').html().replace(/$1/g, id);
            $('.cartcontainer').append(html);
        });
    } else {
        console.log('invalid response', response);
    }
}