微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript-jQuery $.ajax()及其成功回调-它返回哪里?

jQuery ajax成功回调返回到哪里?

我编写了一个请求方法,该方法进行ajax调用,检测是否提供了回调或返回了响应XML的datanode.

请求方法

function request(request, dontRefresh)
{     
   var requestXML = composeRequestXML(request); 
   $.ajax({
      url: 'someProcessor.PHP',
      type: 'POST',
      cache: false,
      async: dontRefresh,
      timeout: 5000,
      data: "query="+requestXML,
      success: function(response)
      {
         //parses xml into a js object
         var responSEObj = parseResponseXML(response);

         if(request.callback){
            request.callback(responSEObj);
         } else {
            // responSEObj.response[0].data[0] is the data 
            // node of the response Obj.
            // this is what i see being the problem - 
            // I DON'T KNow WHERE THIS IS RETURNED TO!!
            return responSEObj.response[0].data[0];
         }
      }
   });
}

该请求将使用回调

var requestObj = new Object();
    requestObj.callback = function(responSEObj){someCallbackFunction(responSEObj);};
    requestObj[0] = new Object();
    requestObj[0].module = "someModule";
    requestObj[0].action = "someModuleMethod";
request(requestObj);
//results are returned to the function someCallbackFunction()

这是我想完成的一个例子

var requestObj = new Object();
    requestObj[0] = new Object();
    requestObj[0].module = "userManager";
    requestObj[0].action = "GET_USERID";

var userId = request(requestObj, false); //make the request asynchronous

我试过返回$.ajax()函数本身…像这样:

function request(request, dontRefresh){
   return $.ajax({/*...options...*/);
}

但这绕过了我开发的xml解析器,并返回了XHR对象.我想使用这种技术来注册变量.所以本质上…

我将在回调中使用此方法,或使用它设置变量.

解决方法:

它返回给jquery,jquery丢弃它.如果要在加载某些内容之前停止代码,请使用同步ajax.但这会使页面无响应,直到ajax请求完成为止,所以请不要这样做!

同步ajax的示例(无jQuery):

var ajax=new XMLHttpRequest();
ajax.open("GET", url, false);
ajax.send(null);
return ajax.responseText;

注意:为了实现IE兼容性,这会变得有些复杂,这只是概念上的证明.这就是这样做的jQuery方式:How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐