2013-06-12 83 views
1

我正在通过ajax调用api。显示结果最简单的方法是什么?如果我提醒结果,我只是得到[对象对象],如果我试图提醒我知道返回的json结果(例如results.title),我只是得到'未定义'的错误。ajax json请求,如何显示结果?

代码即时通讯使用的样子:

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

我试图parseJSOn,但我得到一个错误与到,意外的标记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像上面的,只是更多项目

+1

在浏览器中访问该URL以查看它返回的内容。 –

+0

它返回一个json数组,更新我的问题 – rpsep2

+0

更可能是一个对象数组,因此您需要尝试结果[0] .title,但没有看到数据返回它无法回答。 – DAC84

回答

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 
    } 
} 

FIDDLE

如果您使用的浏览器 - 它可以很容易通过做的console.log和检查控制台

+0

这种帮助...我现在得到一个不同的问题,编辑原始问题 – rpsep2

+0

@ rpsep2你可以粘贴整个json在jsfiddle.net? –

+0

@ rpsep2啊..我知道它出错了我会重写我的回答 –

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/