Ajax - JSON响应不能很好地读取id数组

Ajax - JSON Response is not reading well an array of ids

本文关键字:读取 id 数组 很好 不能 JSON 响应 Ajax      更新时间:2023-09-26

下面是我的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方法被调用时,警报函数给出一个结果,而不是许多单个id。

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

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

我想不知何故我的代码没有正确读取json。你能帮我解决这个问题吗?

提前感谢!

只需将$.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>

当数组被放置在不能表示为文字数组的环境中时,JavaScript会自动格式化数组。所以你的代码仍然是一个数组,只是没有按照你想要的方式格式化。

使用JSON.stringify将JavaScript数组格式化为数组,但在内存中表示为字符串,以下是一个示例:

alert(JSON.stringify(data.colorids));

下面是一个例子,说明你的数据仍然是一个有效的数组,只是表示不同:

var myArray = ['foo', 'bar'];
alert(myArray); // foo,bar
myArray[0]; // 'foo'

根据@blex的回答,我可能误解了你想要的结果。

你必须遍历数组以获得单个值,这可以通过多种方式完成。

只是为了不复制blex的答案,你可以使用本地替代Array.prototype.forEach:

data.colorids.forEach(function(color){
  alert(color);
});