我有一个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({
  url: '//.xml',
  dataType: 'xml',
  success: onTrue,
  error: function (err) {
      console.error('Error: ', err);
  }
});

$('a').each(function () {
  $(this).click(function (e) {
      var l = e.target.text;
      //array.sort(sorteerOp(l));
      //functionToAdaptHtml();
  });
});

其他回答

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

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

这就会打印标记

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+'</>');
}
});
 $(document).ready(function () {
    $.ajax({ 
        url: '/functions.php', 
        type: 'GET',
        data: { get_param: 'value' }, 
        success: function (data) { 
         for (var i=0;i<data.length;++i)
         {
         $('#cand').append('<div class="name">data[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
        }));
    });
});

好吧,我也有同样的问题,我通过从[{"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']);
       ..
    }

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