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 关注
- 362 浏览
添加回答
举报