2012-03-20 111 views
0
var myurl="https://raw.github.com/currencybot/open-exchange-rates/master/latest.json"; 

    $.ajax(
    { 
    url:myurl, 
    type:"POST", 
    dataType:"JSONP", 
    success:function(myObj) 
     { 
     console.log(myObj); 
     } 
    }); 

我嘗試使用簡寫getJSON,但控制檯拋出錯誤「使用POST請求」。 並使用上面的代碼,控制檯指出「無效標籤」。無法獲得json響應

回答

0

你應該改變的代碼,試試這個:

$.post(
    myurl, 
    {}, 
    function(data){ 
    alert(data); 
    },'json' 
); 

變量 '數據' 是一個JSON對象。

+0

感謝,但這個沒有工作.. – 2012-03-20 06:50:30

+0

錯誤引用上:「」NetworkError:404 Not Found - https://raw.github.com/currencybot/open-exchange-rates/master/latest.json「」 – 2012-03-20 06:50:46

+0

你不需要給它們pty'{}' – Starx 2012-03-20 07:10:24

0

跨域JSONP根本就不是AJAX。它不使用XMLHttpRequest。它不過是一個加載JavaScript代碼的動態腳本元素。

嘗試:


var req = $.ajax({ 
    url : myurl, 
    dataType : "jsonp" 
}); 

req.success(function(myObj) { 
    console.log(myObj); 
}); 

req.error(function() { 
    console.log('some error occured'); 
}); 

我認爲高端服務器 「https://raw.github.com」 不支持JSONP。因此,您可能必須在您的服務器上創建代理端點才能訪問此數據。基本上,在你自己的服務器上創建一個端點,使用任何有意義的方法(curl等)加載該數據,並按原樣返回它。然後你可以使用常規的AJAX。希望有幫助

+0

如何更改代碼以使其工作? – 2012-03-20 06:51:55

+0

看到編輯的代碼的答案,希望它有助於 – 2012-03-20 07:03:49

+0

其仍然安寧同樣的錯誤..「無效標籤」 – 2012-03-20 07:31:47

1

使用$.getJSON(),它也是速記功能也很有效。

var myurl="https://raw.github.com/currencybot/open-exchange-rates/master/latest.json"; 

$.getJSON(
    myurl, 
    function(data) { 
     //manipulate your json 
}); 

但對於JSONP請求時,你應該有回調參數的URL

如文檔[here]

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.