jQuery $.post processing JSON response

2022-08-30 22:35:35

我无法弄清楚如何从jQuery $.post()请求中正确读取我的JSON响应。

在下面的jQuery代码中,我根据相应的“color_entry_id”从DOM中的元素填充字符串的关联数组,我将其用作键:

var image_links = {};
$(this).find('input[name="color_id"]').each(function() {
    var color_entry_id = $(this).val();
    var image_link = $(this).parent().find('input[name="edit_image"].' + color_entry_id).val();
    image_links[color_entry_id] = image_link;
});

然后我发出POST请求,发送我的“image_links”数组:

$.post(
    "test.php",
    { id: product_id, "images[]": jQuery.makeArray(image_links) },
    function(data) {
        var response = jQuery.parseJSON(data);
        $.each(response.images, function(index, item) {
             alert(item);
        });
    }
);

另外,如上所示,我尝试遍历响应数组并输出每个项目,我希望它是一个字符串,但我只得到“[对象对象]”作为警报值。我不知道如何让它显示我试图显示的字符串!

以下是用于测试的 PHP 代码.php:

<?php
    $product_id = $_POST['id'];
    $images = $_POST['images'];

    $response = array();
    $response['id'] = $product_id;
    $response['images'] = $images;

    echo json_encode($response);
?>

以下是 DOM 的相关部分:

<input type='hidden' value='{{ color_entry_id }}' name='color_id' />
<p><img src='{{ color_img_link }}' /></p>
<p>Image Link: <input class='{{ color_entry_id }}' name='edit_image' type='text' size='150' value='{{ color_img_link }}' /></p>
<div class='colors {{ color_entry_id }}'>
    <div class='img_color'>
        <a href='javascript:void' style='background:...' class='selected'></a>
        <p>...</p>
    </div>
</div>

我想知道我是否在PHP端错误地执行了JSON编码,或者我只是在jQuery中错误地循环了响应。任何帮助都非常感谢!


答案 1

那好吧。。您从帖子中返回的数据对象是:{"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/‌​223"}]};

如果您更改了提醒,就会找到您要查找的值:

$.post(
    "test.php",
    { id: product_id, "images[]": jQuery.makeArray(image_links) },
    function(data) {
        var response = jQuery.parseJSON(data);

        var images = response.images[0];
        for (var i in images){
            alert(images[i]);
        }
    }
);

答案 2

$.post 默认需要 xml,您需要指定响应格式

$.post(
    "test.php",
    { id: product_id, images : jQuery.makeArray(image_links) },
    function(response) {
        // Response is automatically a json object
        for(var i = 0; i < response.images.length; i++) {
            alert(response.images[i]);
        }
    }, 'json' // <-- HERE
);

此外,请考虑在 php 脚本中添加内容类型标头

    <?php
    header("Content-type: application/json"); // Adding a content type helps as well
    $product_id = $_POST['id'];
    $images = $_POST['images'];

    $response = array();
    $response['id'] = $product_id;
    $response['images'] = $images;

    echo json_encode($response);
    ?>

推荐