我想在下面的getJsonData函数中返回xhr.responseText,该如何做?
function getJsonData(method, url){
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
return xhr.responseText;
}
};
xhr.send();
}
哈,已解决
function getAndDealJsonData(method, url, callback){
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.onreadystatechange = function(){
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
callback && callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
}
因为这是一个异步方法,不能直接返回,应该再传进去一个回调函数来取到结果