How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

后端 未结 14 2890
暗喜
暗喜 2020-11-21 05:07

I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an

14条回答
  •  天命终不由人
    2020-11-21 06:00

    I used the answer given by Carcione and modified it to use JSON.

     function getUrlJsonSync(url){
    
        var jqxhr = $.ajax({
            type: "GET",
            url: url,
            dataType: 'json',
            cache: false,
            async: false
        });
    
        // 'async' has to be 'false' for this to work
        var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};
    
        return response;
    }    
    
    function testGetUrlJsonSync()
    {
        var reply = getUrlJsonSync("myurl");
    
        if (reply.valid == 'OK')
        {
            console.dir(reply.data);
        }
        else
        {
            alert('not valid');
        }    
    }
    

    I added the dataType of 'JSON' and changed the .responseText to responseJSON.

    I also retrieved the status using the statusText property of the returned object. Note, that this is the status of the Ajax response, not whether the JSON is valid.

    The back-end has to return the response in correct (well-formed) JSON, otherwise the returned object will be undefined.

    There are two aspects to consider when answering the original question. One is telling Ajax to perform synchronously (by setting async: false) and the other is returning the response via the calling function's return statement, rather than into a callback function.

    I also tried it with POST and it worked.

    I changed the GET to POST and added data: postdata

    function postUrlJsonSync(url, postdata){
    
        var jqxhr = $.ajax({
            type: "POST",
            url: url,
            data: postdata,
            dataType: 'json',
            cache: false,
            async: false
        });
    
        // 'async' has to be 'false' for this to work
        var response = {valid: jqxhr.statusText,  data: jqxhr.responseJSON};
    
        return response;
    }
    

    Note that the above code only works in the case where async is false. If you were to set async: true the returned object jqxhr would not be valid at the time the AJAX call returns, only later when the asynchronous call has finished, but that is much too late to set the response variable.

提交回复
热议问题