我正在尝试使用一个函数向我的服务器调用一个请求json数据的ajax请求。如果我在ajax函数中通过控制台输出resp
变量,它将成功显示数据。如果我尝试将ajax函数设置为一个变量,然后对该变量进行控制台操作,它将返回undefined。有没有办法让函数请求数据,然后将ti设置为要进行控制的变量?
function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp;
}
}
xhr.send();
}
jsonString = jsonData(http://mywebsite.com/test.php?data=test);
console.log(jsonString);
发布于 2012-11-14 05:35:13
这其实很简单..将您的调用更改为by synchronous..
xhr.open("GET", URL, false);
也就是说,这将阻塞浏览器,直到操作完成,如果您可以使用回调,那么它可能是首选的。
function jsonData(URL, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
cb(resp);
}
}
xhr.send();
}
jsonData("http://mywebsite.com/test.php?data=test"
, function(data) { console.log(data); });
https://stackoverflow.com/questions/13373513
复制