如何解析与jQuery / JavaScript的JSON数据? [英] how to parse json data with jquery / javascript?

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

问题描述

我有一个Ajax调用返回一些JSON是这样的:

I have a ajax call that returns some json like this:

$(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 DIV我会得到:

Inside the #cand div I'll get:

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

如何通过这些数据我循环,并将每个名字在一个div?

How can I loop through this data and place each name in a div?

推荐答案

假设你的服务器端脚本没有设置正确的内容类型:应用程序/ JSON 响应头你需要告诉jQuery的,这是JSON使用数据类型:'json的参数

Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.

然后,你可以使用 $。每() 通过数据功能循环:

Then you could use the $.each() function to loop through the data:

$.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
        }));
    });
});

这篇关于如何解析与jQuery / JavaScript的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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