问题
i have a problem with Ajax Request ( Basic function )
here's ajax function
function ajax(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]
if (window.ActiveXObject){
for (var i=0; i<activexmodes.length; i++){
try{
return new ActiveXObject(activexmodes[i])
}
catch(e){
}
}
}
else if (window.XMLHttpRequest)
return new XMLHttpRequest()
else
return false
}
here is another function
_2xm.load = function (p, type)
{
p = p.replace("frame_", "");
loading(type);
var req=new ajax();
var __page =encodeURIComponent(p);
req.open("GET", "page.php?page="+__page, true);
req.send(null);
req.onreadystatechange=function(){
if (req.readyState==4)
{
if (req.status==200 || window.location.href.indexOf("http")==-1)
{
loading(2);
return req.responseText;
}
else
{
loading(2);
return "An error was occured.... ";
}
}
}
}
here is part of code which uses _2xm.load() function :
_2xm.loadData = [_2xm.load(pg, 0), _2xm.now(), _2xm.interval * 60];
but the result is allways Undefined, why?
回答1:
You never returned a value from _2xm.load, so the function implicitly evaluates to undefined.
You return values only from the anonymous function callback bound to req.onreadystatechange, which fires at some later stage, asynchronously, long after your function call to _2xm.load has finished.
Perhaps you should consider a synchronous request.
来源:https://stackoverflow.com/questions/6776719/ajax-request-returns-undefined-result