我想在一个函数中放一个ajax调用,因为我在多个位置重复使用它。我想要一个被操纵的响应版本返回。这是我正在尝试做的事情(大大简化)。
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
然而,正在发生的事情是,在getAjax函数中定义“a”之前,append函数正在运行。有什么想法吗?
答案 0 :(得分:14)
AJAX是异步的。这意味着成功处理程序中的代码会延迟,直到请求成功,而其余代码将继续正常运行。您需要将相关代码放在AJAX成功处理程序中:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
请注意,我还使用原生Javascript body
优化了您的document.body
选择器,而非使用标准代码选择器。
修改回调版
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
现在可以使用回调函数来内联代码:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
或
getAjax(function(response) {
alert(response);
});
或其他什么。
当AJAX请求完成时,将处理匿名函数调用中的代码。
答案 1 :(得分:8)
标记此方法有两种方法。一个是使用成功回调:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
另一种是将异步设置为false http://api.jquery.com/jQuery.ajax/:
var a;
getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
async: false,
success: function(response) {
a = response;
});
}
关于非异步的重要说明:
跨域请求和dataType:“jsonp”请求不支持同步操作。
答案 2 :(得分:2)
我的一个建议是将触发器传递给您想要运行到AJAX函数的命令,以便它在AJAX收到响应后运行 -
a = getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
inputText(response);
});
}
inputText(someText) {
$(document.body).append('<div>'+ someText +'</div>');
}
这样你就可以创建if语句/其他替代方法来继续对不同的结果使用相同的AJAX命令
答案 3 :(得分:1)
为什么不在成功回调中将响应返回给另一个函数。这应该可以满足您对不同响应的需求:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
}
function AppendResponse(response) {
$('body').append('<div>'+response+'</div>');
}
答案 4 :(得分:0)
您可以为函数getAjax()
提供处理程序,但是如果用户需要下一个决定的信息,那么为什么不使用async: false
呢?
function getAjax(handler) {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
handler(response);
});
};
function callGetAjax(response) {
if(response === undefined) {
getAjax(callGetAjax);
} else {
$('body').append('<div>'+response+'</div>');
}
}