简体   繁体   中英

How to do a synchronous json ajax call with jquery

I have the following json ajax call:

$.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?

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

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?

By default, all requests are sent asynchronously (ie 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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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