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");
}
}
感谢。你的解释非常有帮助。我已经消除了XHR对象的使用,并且使用您提供的附加代码,现在我可以访问回调函数中定义的变量。 – user1973057