2013-08-16 40 views
10

我試圖通過jQuery從這個URLjQuery的跨域請求獲得JSON應答,而不回調

http://www.iheartquotes.com/api/v1/random?format=json 

檢索JSON。我知道解決方案是JSONP,但由於我無法控制服務的響應文本或將其包裝在自己的回調函數中,我的目標是以某種方式使用客戶端腳本檢索上述URL的響應。

我嘗試了幾乎所有從StackOverflow的答案建議的所有方法。 這些是我嘗試過的代碼塊和我得到的響應。

1。它返回預期的訪問控制允許來源錯誤

$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json", 
    function(data) { 
    alert(data);   
    }); 

響應的直接調用:

XMLHttpRequest cannot load =1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.

2。與回調參數上面的代碼中加入:

$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?", 
    function(data) { 
    alert(data);   
    }); 

響應:

Uncaught SyntaxError: Unexpected token :

請注意,當我點擊了錯誤,它帶我到預期的JSON響應。

{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"} 

這也是預期的,因爲在響應中沒有定義回調函數。

3。通過jQuery的阿賈克斯方法

$.ajax({ 
    type: "GET", 
    dataType: "jsonp", 
    url: "http://www.iheartquotes.com/api/v1/random?format=json", 
    success: function(data){   
    alert(data); 
    }, 
}); 

響應:

Uncaught SyntaxError: Unexpected token :

添加回調參數上面的功能沒有改變的響應。

從專家的任何幫助或指針從URL檢索JSON?我正在從Chrome開發工具測試這個。我知道我可以從服務器端代碼調用服務,然後將其發送到客戶端。但我想看看是否可以通過客戶端單獨的jQuery來完成。

編輯: 基於Kevin B的評論: 通過使用jQuery的Ajax通過YQL獲得預期的輸出。但是我的問題依然如此。有沒有一種原生的方式通過jQuery來完成它,因爲YQL仍然是一個依賴項?

// Using YQL and JSONP 
$.ajax({ 
    url: "http://query.yahooapis.com/v1/public/yql", 

    // the name of the callback parameter, as specified by the YQL service 
    jsonp: "callback", 

    // tell jQuery we're expecting JSONP 
    dataType: "jsonp", 

    // tell YQL what we want and that we want JSON 
    data: { 
     q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"", 
     format: "json" 
    }, 

    // work with the response 
    success: function(response) { 
     console.log(response.query.results.json); // server response 
    } 
}); 

這給出了預期的響應。

+2

沒有服務器端干預是不可能的。請注意,它不一定是* your * server,google YQL。 –

+1

或者在這裏看到這篇文章:http://learn.jquery。com/ajax/working-with-jsonp/ –

+0

嗨@KevinB,謝謝YQL指針。您的建議在某種程度上起作用。我編輯了我的問題以包含新的代碼。 –

回答

1

這不會在所有的瀏覽器,但根據其中的JQuery的版本你使用try:

$.support.cors = true; 

顯然,這還取決於服務器響應的標頭。