Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

javascript - 如何让jQuery执行同步而不是异步的Ajax请求?(How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?)

I have a JavaScript widget which provides standard extension points.

(我有一个提供标准扩展点的JavaScript小部件。)

One of them is the beforecreate function.

(其中之一是beforecreate函数。)

It should return false to prevent an item from being created.

(它应该返回false以防止创建项目。)

I've added an Ajax call into this function using jQuery:

(我已经使用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);
  });
}

But I want to prevent my widget from creating the item, so I should return false in the mother-function, not in the callback.

(但是我想防止我的小部件创建项目,因此我应该在母函数中而不是在回调中返回false 。)

Is there a way to perform a synchronous AJAX request using jQuery or any other in-browser API?

(有没有一种方法可以使用jQuery或任何其他浏览器内API执行同步AJAX请求?)

  ask by Artem Tikhomirov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the jQuery documentation : you specify the asynchronous option to be false to get a synchronous Ajax request.

(从jQuery文档中 :您将异步选项指定为false,以获取同步Ajax请求。)

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
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...