[英]jquery $.ajax() and its success callback - where is it returning to?
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這樣做的方式: 我如何讓jQuery執行同步而非異步的Ajax請求?
從您的角度來看,該功能不會返回任何地方。 返回值丟失。
異步處理的關鍵是您處理與事件處理程序中的事件關聯的任何數據,或從那里傳遞它。
/* ... */
success: function(response)
{
//parses xml into a js object
var responseObj = parseResponseXML(response);
if(request.callback){
request.callback(responseObj);
} else {
/* do something with the data */
setUserId(responseObj.response[0].data[0]);
}
}
其中setUserId()
是一個有用的函數,只要用戶ID可用。
responseObj.response[0].data[0]
,您可能不應該使用responseObj.response[0].data[0]
而不確定該值是否實際存在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.