2012-03-28 49 views
0

我試圖使用NYT api來工作,但我不斷收到不同的錯誤。我試圖用這個無法獲取Ajax與鍵控api配合使用

$.ajax({ 
    url:"http://api.nytimes.com/svc/news/v3/content/all/all/.json?api-key=xxxxxxxxxxxxxxxxxxxxx:xx:xxxxxxxxxx&callback=?", 
    dataType: 'jsonp', 
    success:function(json){ 
     alert("Success"); 
    }, 
    error:function(){ 
     alert("Error"); 
    }, 
}); 

當我運行此我得到

 Uncaught SyntaxError: Unexpected token : 

我知道做跨域請求的影響,但我不知道如果我eveing這樣做的權利

+0

它看起來像一個無效的URL。與jQuery無關。 – gdoron 2012-03-28 18:13:57

+0

它看起來像是希望你的api-key的格式爲&api-key = {xxxxxxxxxxxxxxxxxxxxxxxx-xxxxx}?回調不是'?api-key' – Ohgodwhy 2012-03-28 18:22:05

+0

@gdoron他的URL看起來無效嗎?除了?而不是api-key前面的&,這是構建NYT API的URI請求的正確方法。檢查他鏈接的API。 – Ohgodwhy 2012-03-28 18:22:57

回答

0

從(RFC 1738 12月94):

只有字母數字[0-9A-ZA-Z],特殊字符 「$ -_。+!*'(),」[不包括引號],以及用於其保留目的的保留字符 可以在URL內未經編碼使用。

所以,你需要要麼使AJAX調用之前手動編碼URI或'data'對象傳遞的參數:

$.ajax({ 
    url:"http://api.nytimes.com/svc/news/v3/content/all/all/.json", 
    data: {"api-key":"xxxxxxxxxxxxxxxxxxxxx:xx:xxxxxxxxxx"}, 
    dataType: 'jsonp', 
    success:function(json){ 
     alert("Success"); 
    }, 
    error:function(){ 
     alert("Error"); 
    }, 
}); 

而且我不specifiying「callback=?」參數,因爲jQuery ajax會自動發送,如果dataTypejsonp

+0

沒有運氣,現在即時獲取跨域警告 – alexdmejias 2012-03-28 18:46:47

+0

@ alme1304你可以提供一個'nytimes api'' s鏈接,它被提及關於支持jsonp? – Engineer 2012-03-28 19:04:36

+0

是否有另一種跨域的方式? – alexdmejias 2012-03-28 21:57:55

1

所有你缺少的是在url中更改.json.jsonp

你的代碼是正確的,但如果你看看返回的響應,你會發現它實際上並不是一個jsonp響應;它只是一個普通的json有效載荷。

添加回調參數不會導致NYT API自動返回jsonp。如果您想要jsonp,請使用.jsonp格式並提供回調參數。調用該方法只指定dataType: 'jsonp'而不是jsonp: 'jsonp'或類似的東西,當

http://api.nytimes.com/svc/news/v3/content/all/all/.jsonp?limit=10&api-key={my key}

然後:

+0

碰到同樣的問題。這解決了它。謝謝! – wali 2014-09-16 16:40:41

0

我解決了這個問題,我在我的請求URL指定JSONP。

相關問題