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


当前回答

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

let data = '{ "name": "mark"}'
let object = JSON.parse(data);
console.log(object.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
        }));
    });
});

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

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

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

dataType:'json'

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

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