我有一个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 div中,我将得到:

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

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


当前回答

使用那个代码。

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

其他回答

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

//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+'</>');
        }
    }
});

假设你的服务器端脚本没有设置正确的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
        }));
    });
});

使用那个代码。

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

我同意上面所有的解决方案,但是要指出这个问题的根本原因是什么,上面所有代码中的主要角色是这行代码:

dataType:'json'

如果漏掉了这一行(这是可选的),从服务器返回的数据将被视为完整长度的字符串(这是默认的返回类型)。添加这行代码通知jQuery将可能的json字符串转换为json对象。

任何jQuery ajax调用都应该指定这一行,如果期望json数据对象。

Json数据

data = {"clo":[{"fin":"auto"},{"fin":"robot"},{"fin":"fail"}]}

当检索

$.ajax({
  //type
  //url
  //data
  dataType:'json'
}).done(function( data ) {
var i = data.clo.length; while(i--){
$('#el').append('<p>'+data.clo[i].fin+'</>');
}
});