dwe*_*lch 8 javascript ajax jquery
I would like to put an ajax call within a function since I use it repeatedly in multiple locations. I want a manipulated version of the response returned. Here's what I'm trying to do (greatly simplified).
a = getAjax();
$('body').append('<div>'+a+'</div>');
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
return response;
});
}
Run Code Online (Sandbox Code Playgroud)
然而,正在发生的是,在getAjax函数中定义"a"之前,append函数正在运行.有什么想法吗?
lon*_*day 14
AJAX是异步的.这意味着成功处理程序中的代码会延迟,直到请求成功,而其余代码将继续正常运行.您需要将相关代码放在AJAX成功处理程序中:
getAjax();
function getAjax() {
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
$(document.body).append('<div>'+response+'</div>');
});
}
Run Code Online (Sandbox Code Playgroud)
请注意,我还body使用本机Javascript document.body而不是使用标准标记选择器来优化您的选择器.
编辑回调版本
function getAjax(callback) {
$.ajax({
type: 'GET',
url: 'someURL',
success: callback
});
}
Run Code Online (Sandbox Code Playgroud)
您现在可以使用回调函数内联代码:
getAjax(function(response) {
$(document.body).append('<div>'+response+'</div>');
});
Run Code Online (Sandbox Code Playgroud)
要么
getAjax(function(response) {
alert(response);
});
Run Code Online (Sandbox Code Playgroud)
管他呢.
当AJAX请求完成时,将处理匿名函数调用中的代码.
标记这个有两种方法.一个是使用成功回调:
$.ajax({
type: "GET",
url: 'someURL',
success: function(response) {
AppendResponse(response);
});
Run Code Online (Sandbox Code Playgroud)
另一种是将异步设置为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;
});
}
Run Code Online (Sandbox Code Playgroud)
关于非异步的重要说明:
跨域请求和dataType:"jsonp"请求不支持同步操作.