如果我在我的 XHR 的 onreadystatechange 函数中,我可以很容易地做到document.title = xhr.responseText
,但是如果我让函数返回 responseText,我不能设置一个等于我的 XHR 的外部包装器的变量来使它等于响应;有什么办法可以做到这一点吗?
我的包装:
ajax = function(url, cb)
{
xhr = (window.XMLHttpRequest)
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
cb(xhr.responseText);
};
}
xhr.open('get', url, true);
xhr.send();
};
现在,如果我做了类似的事情:
ajax('bacon.txt', function(_)
{
document.title = _;
}
它绝对完美;document.title 实际上变成了调用 bacon.txt 的 responseText。但是,如果我尝试以这种方式实现它:
document.title = ajax('bacon.txt', function(_)
{
return _;
}
没有这样的运气。谁能澄清这是为什么?};