简体   繁体   English

如何使用jquery执行同步json ajax调用

[英]How to do a synchronous json ajax call with jquery

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. 我现在需要使它同步,因为我需要暂停调用函数,直到设置has_error。 How do I do this? 我该怎么做呢?

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; 我已经尝试将DataType设置为json,jsonp或不设置; I've tried including the ?callback=? 我试过包括?callback=? and I've tried leaving it off; 我试着把它关掉; none of this has worked. 这一切都没有奏效。 What am I doing wrong? 我究竟做错了什么?

By default, all requests are sent asynchronously (ie this is set to true by default). 默认情况下,所有请求都是异步发送的(默认情况下设置为true)。 If you need synchronous requests, set this option to false. 如果需要同步请求,请将此选项设置为false。 Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. 跨域请求和dataType:“jsonp”请求不支持同步操作。 Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. 请注意,同步请求可能会暂时锁定浏览器,并在请求处于活动状态时禁用任何操作。

As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; 从jQuery 1.8开始,不推荐使用async:false和jqXHR($ .Deferred); you must use the success/error/complete callback options instead of the corresponding method 您必须使用success / error / complete回调选项而不是相应的方法

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

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. 如果需要一些代码来延迟它的执行,直到异步调用完成,那么将该代码放在回调函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM