1

我正在通过 ajax 调用 api。显示结果的最简单方法是什么?如果我提醒结果,我只是得到 [object object],如果我尝试使用我知道返回的 json 中的项目(例如,results.title)来提醒结果,我只会得到一个“未定义”错误。

我使用的代码如下所示:

$.ajax({
    url: 'http://API-LINK-format=json',
    dataType: 'json',
    success: function(results) {
    alert(results.title);
    alert(results)
    }
})

我试图解析JSOn,但我得到一个错误,意外的令牌o。

任何帮助表示赞赏!谢谢

api返回类似:

{"request":
    {
     "format":"json","method":"theMethod","id":"theID"},
     "time":"0.00863",
     "job":{"types":{"type":["Permanent"]},
     "email":"EMAIL",
     "title":"theTitle"
     }
}

只有更多嵌套,更长等

编辑::

使用:

alert(results.request.title);

我仍然收到未定义的警报。我运行了一个每个循环,结果我以某种方式得到了 3 个结果?我运行这段代码:

$.ajax({
    url: 'http://API-LINK-format=json',
    dataType: 'json',
    success: function(results) {
        $.each(results, function(i, result){
             alert(result.title)
        }
    }
})

它会发出 3 次警报,前 2 次未定义,然后第 3 次给了我我需要的东西.. 但就像我说的我知道 api 正在返回一个像上面这样的 json,只是更多的项目

4

2 回答 2

2

你需要

requests.job.title

如果您对其进行格式化,这是您的实际结构

{ // <-- this is your requests object
    "request": { // -- what you want isn't in here -- this is the first element in the each loop
        "format": "json",
        "method": "theMethod",
        "id": "theID"
    },
    "time": "0.00863", // <-- it isn't here either -- this is the second element in the each loop
    "job": { // it's here - so you want request.job -- this is the third
        "types": {
            "type": ["Permanent"]
        },
        "email": "EMAIL",
        "title": "theTitle" // to get this it's request.job.title
    }
}

小提琴

如果您使用的是 Chrome - 通过执行 console.log 并检查控制台可以很容易地检查您的对象

于 2013-06-12T14:34:24.573 回答
0

我想是一个异步问题,试试:

var req = function(){

return $.ajax({
         url: 'http://API-LINK-format=json',
         dataType: 'json',
         success: function(results) {
          console.log('success');
         }
       })
});

req().done(function(data) {
 //do something with data
});

也许我猜错了,但试试这个。

http://api.jquery.com/deferred.done/

于 2013-06-12T14:57:52.533 回答