2013-06-05 77 views
0

我是NOOB,我發現其他用戶遇到類似的問題,但在經歷了許多小時的挫折之後,我無法獲得JSONP回調函數的工作。JSONP回調未定義

我試圖從雅虎geo.places的「WOEID」的信息,所以我可以用它來指定位置獲取天氣數據。我從表單中的「位置」標識中接收輸入(例如郵政編碼)並將其提交給雅虎。

代碼返回一個XMLHttpRequest對象,我可以通過查看控制檯中的xhr.responseText來讀取該對象,但無法提取正由服務器傳遞給回調函數的JSON對象。

我知道我必須做出一個簡單的錯誤,但我無法弄清楚它是什麼。我試圖通過Javascript來學習如何使用jQuery中的$ .ajax方法來檢索數據。

你能告訴我錯誤在哪裏嗎?這裏是我的代碼:

// an XMLTHttpRequest 
var xhr = null; 

/* 
* void 
* getWoeid() 
* gets WOEID from Yahoo geo.places to use in request 
* for weather data 
* 
*/ 



function getWoeid() { 
// instantiate XMLHttpRequest object 
try { 
    xhr = new XMLHttpRequest(); 
} 
catch (e) { 
    xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
} 

// handle old browsers 
if (xhr == null) { 
    alert("Ajax not supported by your browser!"); 
    return; 
} 

// construct URL 
var userinput = document.getElementById("location").value; 

var data = encodeURIComponent("select * from" + 
      " geo.places where text =" + userinput); 

var url = "http://query.yahooapis.com/v1/public/yql?q=" + data + "&format=json& callback=callback"; 


// get data 
xhr.onreadystatechange = handler; 
xhr.open("GET", url, true); 
xhr.send(null); 
} 


// callback function 
function callback(response) { 
    woeid = response; 
} 


/* 
* void 
* handler() 
* 
* Handles the Ajax response 
*/ 

function handler() { 

// only handle loaded requests 
if (xhr.readyState == 4) { 

    // display response if possible 
    if (xhr.status == 200) { 
      var location = woeid; 
    } 

    else  
     alert("Error with Ajax call"); 
} 

}

回答

1

不能使用XHR對象請求,因爲same origin policy的JSONP結果。另外,即使您在本地發出請求,使用XHR對象發出請求也意味着callback函數不會被調用,您只需獲取用於在響應中調用它的代碼即可。

要獲得使JSONP請求,您使用腳本標籤:

var script = document.createElement('script'); 
script.src = url; 
document.head.appendChild(script); 
+0

感謝。你的解釋非常有幫助。我已經消除了XHR對象的使用,並且使用您提供的附加代碼,現在我可以訪問回調函數中定義的變量。 – user1973057