jQuery: Performing synchronous AJAX requests

后端 未结 4 2155
刺人心
刺人心 2020-11-22 04:48

I\'ve done some jQuery in the past, but I am completely stuck on this. I know about the pros and cons of using synchronous ajax calls, but here it will be required.

<
相关标签:
4条回答
  • 2020-11-22 05:28

    As you're making a synchronous request, that should be

    function getRemote() {
        return $.ajax({
            type: "GET",
            url: remote_url,
            async: false
        }).responseText;
    }
    

    Example - http://api.jquery.com/jQuery.ajax/#example-3

    PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

    Chrome:

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

    Firefox:

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

    0 讨论(0)
  • 2020-11-22 05:31
    function getRemote() {
        return $.ajax({
            type: "GET",
            url: remote_url,
            async: false,
            success: function (result) {
                /* if result is a JSon object */
                if (result.valid)
                    return true;
                else
                    return false;
            }
        });
    }
    
    0 讨论(0)
  • 2020-11-22 05:36

    You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:

    var remote = $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
    
    0 讨论(0)
  • how remote is that url ? is it from the same domain ? the code looks okay

    try this

    $.ajaxSetup({async:false});
    $.get(remote_url, function(data) { remote = data; });
    // or
    remote = $.get(remote_url).responseText;
    
    0 讨论(0)
提交回复
热议问题