我有一个提供标准扩展点的JavaScript widget。其中一个是 "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);
});
}
但我想阻止我的部件创建项目,所以我应该在母函数中返回false
,而不是在回调中。有没有办法使用jQuery或其他浏览器内的API来执行同步的AJAX请求?
从jQuery文档:你指定asynchronous选项为false来获得一个同步的Ajax请求。然后你的回调可以在你的母函数进行之前设置一些数据。
下面是你的代码,如果按照建议修改,会是什么样子。
beforecreate: function (node, targetNode, type, to) {
jQuery.ajax({
url: 'http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value),
success: function (result) {
if (result.isOk == false) alert(result.message);
},
async: false
});
}
你可以将jQuery的Ajax设置置于同步模式,通过调用
jQuery.ajaxSetup({async:false});
然后用jQuery.get( ...);
执行你的Ajax调用。
然后只需再次打开它一次
jQuery.ajaxSetup({async:true});
我想这和@Adam的建议是一样的,但它可能对那些想重新配置jQuery.get()
或jQuery.post()
到更复杂的jQuery.ajax()
语法的人有帮助。
优秀的解决方案当我试图实现它时,我注意到如果我在成功子句中返回一个值,它就会返回为未定义。我不得不把它存储在一个变量中并返回该变量。这就是我想出的方法。
function getWhatever() {
// strUrl is whatever URL you need to call
var strUrl = "", strReturn = "";
jQuery.ajax({
url: strUrl,
success: function(html) {
strReturn = html;
},
async:false
});
return strReturn;
}