我有一个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");
            }
        });

其他回答

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

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

var jsonP = "person" : [ { "id" : "1", "name" : "test1" },
  { "id" : "2", "name" : "test2" },
  { "id" : "3", "name" : "test3" },
  { "id" : "4", "name" : "test4" },
  { "id" : "5", "name" : "test5" } ];

var cand = document.getElementById("cand");
var json_arr = [];
$.each(jsonP.person,function(key,value){
    json_arr.push(key+' . '+value.name  + '<br>');
    cand.innerHTML = json_arr;
});

<div id="cand">
</div>

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

dataType:'json'

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

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

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

使用那个代码。

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