javascript 如何使用 jquery 进行同步 json ajax 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21885778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:54:32  来源:igfitidea点击:

How to do a synchronous json ajax call with jquery

javascriptjqueryajaxjsonjsonp

提问by Benubird

I have the following json ajax call:

我有以下 json ajax 调用:

$.getJSON(server_data.secure_api+'/e/account/check/?callback=?', queryData,
    function(data) {
        has_error = (data.status == 'failure');
});

Which works perfectly, except that it is asynchronous. I now need to make it synchronous, because I need to pause the calling function until has_error is set. How do I do this?

除了它是异步的之外,它完美地工作。我现在需要使它同步,因为我需要暂停调用函数,直到设置了 has_error。我该怎么做呢?

I have already tried using a .ajax call, like this:

我已经尝试过使用 .ajax 调用,如下所示:

jQuery.ajax({
    url:        server_data.secure_api+'/e/account/check/?callback=?',
    data:       queryData,
    DataType:   'jsonp',
    success:    function(result) {
                has_error = (data.status == 'failure');
            },
    async:      false
});

But it doesn't work! I've tried setting the DataType to json, jsonp, or not set; I've tried including the ?callback=?and I've tried leaving it off; none of this has worked. What am I doing wrong?

但它不起作用!我已经尝试将 DataType 设置为 json、jsonp 或未设置;我试过包括?callback=?,我试过把它关掉;这些都没有奏效。我究竟做错了什么?

回答by bluszcz

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

默认情况下,所有请求都是异步发送的(即默认设置为 true)。如果您需要同步请求,请将此选项设置为 false。跨域请求和 dataType: "jsonp" 请求不支持同步操作。请注意,同步请求可能会暂时锁定浏览器,从而在请求处于活动状态时禁用任何操作。

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding method

从 jQuery 1.8 开始,不推荐使用带有 jqXHR ($.Deferred) 的 async: false ;您必须使用成功/错误/完成回调选项而不是相应的方法

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.ajax/

回答by Spencer Ruport

There's no reason your use case should require synchronous code. If you need some code to delay it's execution until the asynchronous call is completed then place that code in the callback function.

您的用例没有理由需要同步代码。如果您需要一些代码来延迟它的执行,直到异步调用完成,然后将该代码放在回调函数中。