2011-09-20 62 views
1

Possible Duplicate:
JSON crossdomain communication with PHP file and a local javascript file地空沒有被訪問控制允許來源

var xhr = new XMLHttpRequest(); 
xhr.open("GET","http://api.productwiki.com/connect/api.aspxop=search&q=iphone&format=json&ke y=123456789"); 
xhr.onreadystatechange = function(){ 
    if(xhr.readyState=== 4 && xhr.status==200){ 
     console.log(xhr.responseText); 
    } 
} 
xhr.send(); 

我想Ajax請求從以下網址獲得的數據允許的。我去錯誤:

XMLHttpRequest cannot load http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789. Origin null is not allowed by Access-Control-Allow-Origin. 

回答

0

您要求從一個不同的起源,你必須使用JSONP。 JSONP允許您將來自服務器的響應傳遞給JavaScript中的回調函數。最簡單的方法是使用jQuery和使用的getJSON()或AJAX()方法,它會允許你做這樣的事情:

$.getJSON('http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789', 
     yourCallback); 
0

聽起來像web服務不支持CORS這是需要繞過same origin policy

產品wiki webservice api支持JSONP,因此您可以使用它。

它要求您在查詢字符串中設置format=json。它需要你設置一個回調。

//callback function 
function YourGlobalFunction(data){ 
    console.log(data); 

} 

//Fetch the content with JSONP 
var scr = document.createElement("script"); 
scr.src = "http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789&format=json&callback=YourGlobalFunction"; 
document.body.appendChild(scr); 

如果你想要去的簡單,並且可以使用庫如jQuery,它會處理設置回調爲您服務。

jQuery.getJSON(
    "http://api.productwiki.com/connect/api.aspx?op=search&q=iphone&format=xml&key=123456789&format=json", 
    {}, 
    function(data){ 
     console.log(data); 
    } 
); 
相關問題