3 回答

TA貢獻1820條經驗 獲得超10個贊
問題是您不能從異步調用(如AJAX請求)返回值,并且期望它能正常工作。
原因是等待響應的代碼在接收到響應時已經執行。
解決此問題的方法是在回調內部運行必要的代碼success:。這樣,它data只有在可用時才能訪問。
function isSession(selector) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// Run the code here that needs
// to access the data returned
return data;
},
error: function() {
alert('Error occured');
}
});
}
另一種可能性(實際上是同一件事)是在success:回調中調用一個函數,該函數在可用時傳遞數據。
function isSession(selector) {
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
success: function(data) {
// Call this function on success
someFunction( data );
return data;
},
error: function() {
alert('Error occured');
}
});
}
function someFunction( data ) {
// Do something with your data
}

TA貢獻1735條經驗 獲得超5個贊
有很多方法可以獲取jQuery AJAX響應。我將與您分享兩種常用方法:
第一:
使用async = false并在函數內返回ajax-object并稍后獲取響應ajax-object.responseText
/**
* jQuery ajax method with async = false, to return response
* @param {mix} selector - your selector
* @return {mix} - your ajax response/error
*/
function isSession(selector) {
return $.ajax({
type: "POST",
url: '/order.html',
data: {
issession: 1,
selector: selector
},
dataType: "html",
async: !1,
error: function() {
alert("Error occured")
}
});
}
// global param
var selector = !0;
// get return ajax object
var ajaxObj = isSession(selector);
// store ajax response in var
var ajaxResponse = ajaxObj.responseText;
// check ajax response
console.log(ajaxResponse);
// your ajax callback function for success
ajaxObj.success(function(response) {
alert(response);
});
第二:
使用$ .extend 方法并創建一個像ajax這樣的新函數
/**
* xResponse function
*
* xResponse method is made to return jQuery ajax response
*
* @param {string} url [your url or file]
* @param {object} your ajax param
* @return {mix} [ajax response]
*/
$.extend({
xResponse: function(url, data) {
// local var
var theResponse = null;
// jQuery ajax
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: "html",
async: false,
success: function(respText) {
theResponse = respText;
}
});
// Return the response text
return theResponse;
}
});
// set ajax response in var
var xData = $.xResponse('temp.html', {issession: 1,selector: true});
// see response in console
console.log(xData);
您可以根據需要將其放大...

TA貢獻1797條經驗 獲得超4個贊
我在這里看到了答案,盡管有幫助,但它們并不是我想要的,因為我不得不更改很多代碼。
對我有用的事情是在做這樣的事情:
function isSession(selector) {
//line added for the var that will have the result
var result = false;
$.ajax({
type: "POST",
url: '/order.html',
data: ({ issession : 1, selector: selector }),
dataType: "html",
//line added to get ajax response in sync
async: false,
success: function(data) {
//line added to save ajax response in var result
result = data;
},
error: function() {
alert('Error occured');
}
});
//line added to return ajax response
return result;
}
希望可以幫助某人
- 3 回答
- 0 關注
- 393 瀏覽
添加回答
舉報