jQuery $ .post处理JSON响应

Jon*_*ins 15 php jquery json

我无法弄清楚如何从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;
});
Run Code Online (Sandbox Code Playgroud)

然后我发出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);
        });
    }
);
Run Code Online (Sandbox Code Playgroud)

另外,如上所示,我尝试循环遍历响应数组并输出每个项目,我想成为一个字符串,但我只得到"[object Object]"作为警告值.我不知道如何让它显示我想要显示的字符串!

这是test.php的PHP代码:

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

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

    echo json_encode($response);
?>
Run Code Online (Sandbox Code Playgroud)

以下是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>
Run Code Online (Sandbox Code Playgroud)

我想知道是否我在PHP端错误地进行JSON编码,或者我只是在jQuery中错误地循环响应.任何帮助深表感谢!!

lti*_*_sh 29

好的..你从帖子里回来的数据对象是: {"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]);
        }
    }
);
Run Code Online (Sandbox Code Playgroud)


Bry*_*yan 25

$ .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
);
Run Code Online (Sandbox Code Playgroud)

另外,请考虑在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);
    ?>
Run Code Online (Sandbox Code Playgroud)