首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何用jQuery / JavaScript解析JSON数据?

如何用jQuery / JavaScript解析JSON数据?
EN

Stack Overflow用户
提问于 2012-01-21 17:02:16
回答 10查看 1M关注 0票数 203

我有一个AJAX调用,它返回一些JSON,如下所示:

$(document).ready(function () {
    $.ajax({ 
        type: 'GET', 
        url: 'http://example/functions.php', 
        data: { get_param: 'value' }, 
        success: function (data) { 
            var names = data
            $('#cand').html(data);
        }
    });
});

#cand目录中,我将得到:

[ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ]

如何遍历这些数据并将每个名称放在一个div中?

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-01-21 17:09:58

假设您的服务器端脚本没有设置正确的Content-Type: application/json响应头,您需要使用dataType: 'json'参数向jQuery表明这是JSON。

然后,您可以使用$.each()函数遍历数据:

$.ajax({ 
    type: 'GET', 
    url: 'http://example/functions.php', 
    data: { get_param: 'value' }, 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

或者使用$.getJSON方法:

$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});
票数 299
EN

Stack Overflow用户

发布于 2012-01-21 17:06:44

设置dataType:'json'将为您解析JSON:

$.ajax({
  type: 'GET',
  url: 'http://example/functions.php',
  data: {get_param: 'value'},
  dataType: 'json',
  success: function (data) {
    var names = data
    $('#cand').html(data);
  }
});

或者,您可以使用parseJSON

var parsedJson = $.parseJSON(jsonToBeParsed);

然后,您可以迭代以下内容:

var j ='[{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]';

使用$().each的...by

var json = $.parseJSON(j);
$(json).each(function (i, val) {
  $.each(val, function (k, v) {
    console.log(k + " : " + v);
  });
}); 

JSFiddle

票数 86
EN

Stack Overflow用户

发布于 2015-09-16 02:39:56

尝试下面的代码,它可以在我的项目中工作:

//start ajax request
$.ajax({
    url: "data.json",
    //force to handle it as text
    dataType: "text",
    success: function(data) {

        //data downloaded so we call parseJSON function 
        //and pass downloaded data
        var json = $.parseJSON(data);
        //now json variable contains data in json format
        //let's display a few items
        for (var i=0;i<json.length;++i)
        {
            $('#results').append('<div class="name">'+json[i].name+'</>');
        }
    }
});
票数 29
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8951810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档