Ajax - JSON Response不能很好地读取一组id

时间:2015-08-23 19:30:42

标签: javascript php jquery ajax json

这是我的javascript代码:

$.ajax({
    url: './checkcolors.php',
    type: 'post',
    data: {
        url: '<?php echo $LINK;?>',
        SizeId: SelectedSizeID
    },
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {                             
                alert(data.colorids);

        });
    }
});

checkcolors.php的结果如下:

{"colorids":["24604603","24604684","24604640","24604609","24604682","24604686","24604681","24604689","24604602","24604679","24604680","24604622","24604685","24604683","24604621","24604677","24604688"]}

当调用Ajax post方法时,alert函数会给出 ONE 结果,而不是其中包含单个id的多个结果。

警报的结果是单一的,它是这样的:

24604603,24604684,24604640,24604609,24604682,24604686,24604681,24604689,24604602,24604679,24604680,24604622,24604685,24604683,24604621,24604677,24604688

我认为我的代码不能正确地读取json。你能帮我解决这个问题吗?

提前致谢!

1 个答案:

答案 0 :(得分:1)

只需将$.each应用于data.colorids数组,而不是包装data对象:

$.each(data.colorids, function(index, element) {                             
    alert(element);
});

<强>演示

var data = {"colorids":["24604603","24604684","24604640","24604609","24604682","24604686","24604681","24604689","24604602","24604679","24604680","24604622","24604685","24604683","24604621","24604677","24604688"]};

$.each(data.colorids, function(index, element){
    console.log(element);
    // Open your console (don't want everybody to be bothered with tons of alerts)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>