我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 我有一个JavaScript小部件,它提供标准的扩展点.其中之一就是beforecreate功能.它应该返回false以防止创建项目.
我使用jQuery在这个函数中添加了一个Ajax调用:
beforecreate: function (node, targetNode, type, to) {
jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
function (result) {
if (result.isOk == false)
alert(result.message);
});
}
Run Code Online (Sandbox Code Playgroud)
但我想阻止我的小部件创建项目,所以我应该返回false母函数,而不是回调.有没有办法使用jQuery或任何其他浏览器中的API执行同步AJAX请求?