javascript Ajax responseText 返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4672691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax responseText comes back as undefined
提问by nnbz
I'm having problems with this piece of code; the return value comes back as 'undefined'. What's the problem?
这段代码有问题;返回值返回为“未定义”。有什么问题?
var fx = null;
xmlhttp.open("GET", URL ,false);
xmlhttp.onreadystatechange=function()
{
alert("enter func");
if (xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
alert(fx);
fx = xmlhttp.responseText;
return fx;
}
else
{
alert("Error" + xmlhttp.statusText);
}
}
}
Newer code:
较新的代码:
function getData(callback)
{
xmlhttp.open("GET", URL ,false);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
alert(xmlhttp.responseText);
cbfunc(xmlhttp.responseText);
}
else
{
alert("Error" + xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
How I'm calling it:
我如何称呼它:
getData( function cbfoo(txt)
{
//document.form.autodate.value=txt;
alert(txt);
alert(document.form.autodate.value);
});`
回答by Ivo Wetzel
Update based on your edit
根据您的编辑更新
function getData(callback)
{
// you should move the creation of xmlhttp in here
// so you can make multiple getData calls if needed
// if you keep xmlhttp outside the function the different calls to getData will interfere
// with each other
xmlhttp.open("GET", URL ,false); // false should be true, to make it async
...
{
alert(xmlhttp.responseText);
cbfunc(xmlhttp.responseText); // your function gets passed as the
// parameter "callback" but you're
// using "cbfunc" here instead of "callback"
...
getData(function cbfoo(txt) // you can omit the function name here
...
Fixing those issues should make the code work.
解决这些问题应该会使代码工作。
Old answer
旧答案
You're calling the XMLHttpRequest in Synchronousmode, that means that it will blockthe script until the request has finished, since you're assigning the onreadystatechangecallback after the blocking call (that means after the request has already finished) your code never gets notified.
您在同步模式下调用 XMLHttpRequest ,这意味着它将阻塞脚本直到请求完成,因为您在onreadystatechange阻塞调用之后分配回调(这意味着在请求已经完成之后)您的代码永远不会得到通知.
Since the synchronous mode blocks the script, it also blocks the Browser's UI, so it's not recommended to use this mode.
由于同步模式会阻塞脚本,也会阻塞浏览器的UI,所以不推荐使用这种模式。
You should (for 99% of the cases) use the Asynchronousmode and use a callback to handle the data, since xmlhttp.opendoes notreturn the return value of the onreadystatechangecallback, it simply returns undefinedimmediately when run in async mode.
你应该(为99%的情况)使用异步模式,并使用一个回调来处理数据,因为xmlhttp.open它没有返回的返回值onreadystatechange的回调,它只是返回undefined在异步模式下运行时立即。
Now a common pattern is to write a wrapper for the request and pass an anonymousfunction to this wrapper, which later will get called back when the request has finished.
现在一个常见的模式是为请求编写一个包装器,并将一个匿名函数传递给这个包装器,稍后在请求完成时会回调它。
function doRequest(url, callback) {
var xmlhttp = ....; // create a new request here
xmlhttp.open("GET", url, true); // for async
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
// pass the response to the callback function
callback(null, xmlhttp.responseText);
} else {
// pass the error to the callback function
callback(xmlhttp.statusText);
}
}
}
xmlhttp.send(null);
}
You can now do a request and supply a function that will get called as soon as the request finishes, inside of that function you then do whatever you want to do with the response.
您现在可以执行请求并提供一个函数,该函数将在请求完成后立即被调用,然后在该函数内您可以对响应执行任何您想做的操作。
doRequest('http://mysite.com/foo', function(err, response) { // pass an anonymous function
if (err) {
alert('Error: ' + err);
} else {
alert('Response: ' + response);
}
});
This is the common programming model in the browser, always go with a asynchronous solution, if you block the script you block the whole Browser.
这是浏览器中常见的编程模型,始终采用异步解决方案,如果您阻止脚本,则会阻止整个浏览器。

