如何使用$ .each和ajax来获取JSON?

时间:2015-08-12 14:04:20

标签: javascript jquery ajax json

我正在使用ajax从API获取JSON,但是我遇到了问题,检索数据。 ajax函数的代码很好,因为我在其他地方使用它。我认为问题出在.done(function()

        $.ajax({
            url: "http://127.0.0.1:4001/Barratt/getData.php",
            //dataType: 'json',
            //method: 'GET',
            //contentType: 'application/json'
            data: {url: developmentURL},
            method: 'POST'
        })
        .done(function(data) {
            //var developments = [];
            $.each(data, function() {
                $.each(this, function(i, obj) {
                    console.log(i, obj.Name + ' = ' + obj.ItemKey);
                    //developments.push();
                });
            });
        })
        .fail(function() {
            alert('Failed to fetch data')
        });

这是我正在使用的代码,它只记录0 "undefined=undefined"的负载。但是我让.done(function()在jsfiddle中工作,JSON是硬编码的。所以我不确定问题出在哪里。

以下是fiddle

3 个答案:

答案 0 :(得分:4)

data是字符串类型。在循环之前将字符串解析为JSON:

data = JSON.parse(data);
$.each(data, function() {

答案 1 :(得分:0)

如果您想避免使用JSON.parse,可以将dataType设置为'json',您将自动收到已解析的json响应:

    $.ajax({
        url: "http://127.0.0.1:4001/Barratt/getData.php",
        dataType: 'json', //Uncomment this line
        //method: 'GET',
        //contentType: 'application/json'
        data: {
            url: developmentURL
        },
        method: 'POST'
    })

或者您也可以使用jquery $.getJSON api。

答案 2 :(得分:0)

我假设您检索的数据是根据您的代码的Json数组。 您忘记在$ .each回调函数中添加键和值以循环到每个Json值。

$.ajax({
            url: "http://127.0.0.1:4001/Barratt/getData.php",
            //dataType: 'json',
            //method: 'GET',
            //contentType: 'application/json'
            data: {url: developmentURL},
            method: 'POST'
        })
        .done(function(data) {
            //var developments = [];
            $.each(data, function(key,value) {
                $.each(value, function(subKey, subValue) {
                    console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
                    //developments.push();
                });
            });
        })
        .fail(function() {
            alert('Failed to fetch data')
        });