Ajax Request returns undefined result

僤鯓⒐⒋嵵緔 提交于 2019-12-11 15:08:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!