如何让 jQuery 执行同步而不是异步的 Ajax 请求? [英] How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?
问题描述
我有一个提供标准扩展点的 JavaScript 小部件.其中之一是 beforecreate
函数.它应该返回 false
以防止创建项目.
I have a JavaScript widget which provides standard extension points. One of them is the beforecreate
function. It should return false
to prevent an item from being created.
我已经使用 jQuery 在这个函数中添加了一个 Ajax 调用:
I've added an Ajax call into this function using jQuery:
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 请求?
But I want to prevent my widget from creating the item, so I should return false
in the mother-function, not in the callback. Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?
推荐答案
来自 jQuery 文档:您将 asynchronous 选项指定为 false 以获取同步 Ajax 请求.然后你的回调可以在你的母函数继续之前设置一些数据.
From the jQuery documentation: you specify the asynchronous option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.
如果按照建议进行更改,您的代码将如下所示:
Here's what your code would look like if changed as suggested:
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 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!