JQuery 解析 JSON 数组 [英] JQuery Parsing JSON array

查看:59
本文介绍了JQuery 解析 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSON 输出,如下所示:

I have a JSON output like the following:

["City1","City2","City3"]

我想获取每个城市的名称,我该怎么做?

I want to get each of the city names, how can i do this?

$.getJSON("url_with_json_here",function(json){

});

$.getJSON('url_here', function(data){
    $.each(data, function (index, value) {
      $('#results').append('<p>'+value+'</p>');
        console.log(value);
    });
});

以上似乎不起作用,没有输出任何值.

The above doesn't seem to be working, no values are outputted.

推荐答案

getJSON() 也会在获取后为您解析 JSON,因此从那时起,您将使用一个简单的 Javascript 数组([] 在 JSON 中标记一个数组).该文档还提供了有关如何处理获取的数据的示例.

getJSON() will also parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON). The documentation also has examples on how to handle the fetched data.

您可以使用 for 获取数组中的所有值循环:

You can get all the values in an array using a for loop:

$.getJSON("url_with_json_here", function(data){
    for (var i = 0, len = data.length; i < len; i++) {
        console.log(data[i]);
    }
});

检查您的控制台以查看输出(ChromeFirefox/Firebug、IE).

Check your console to see the output (Chrome, Firefox/Firebug, IE).

jQuery 还提供 $.each() 用于迭代,所以你也可以这样做:

jQuery also provides $.each() for iterations, so you could also do this:

$.getJSON("url_with_json_here", function(data){
    $.each(data, function (index, value) {
        console.log(value);
    });
});

这篇关于JQuery 解析 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆