我有一个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中放置每个名字?


当前回答

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

其他回答

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

dataType:'json'

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

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

设置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:

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

JSFiddle

下面是如何在JavaScript中做到这一点,这是一个非常有效的方法!

let data = '{ "name": "mark"}'
let object = JSON.parse(data);
console.log(object.name);

这就会打印标记

好吧,我也有同样的问题,我通过从[{"key":"value"}]中删除[]来修复它:

在你的PHP文件中让shure像这样打印

echo json_encode(array_shift($your_variable));

在你的成功函数中这样做

 success: function (data) {
    var result = $.parseJSON(data);
      ('.yourclass').append(result['your_key1']);
      ('.yourclass').append(result['your_key2']);
       ..
    }

如果你想,你也可以循环它

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