jquery ajax with async false hangs firefox

2019-02-18 16:15发布

I have a code that calls $.ajax like this :

$.ajax({

                        type: "POST",
                        url: "/sandbox/graphloader/mock3",
                        async: false,
                        data: {calInput1:dates[0], calInput2:dates[1]},
                        success: function(data){
                            data=eval(data);
                            for(var x in data[0]){
                                //alert(data[0][x]);
                                //fill columns here;
                            }

                            fillPercents(column);
                        }});

now, this works in all browsers, other than Firefox. firebug shows it is getting reply back from post, but for some unknown error, it is not displaying the data. What might be the problem ?

3条回答
Bombasti
2楼-- · 2019-02-18 16:52

This behavior is by design.

Never use async: false.
Since Javascript runs on the UI thread, an async: false request will freeze the browser until the server replies.

查看更多
\"骚年 ilove
3楼-- · 2019-02-18 16:53

Your columns global might be getting overwritten by a previous AJAX request.

Try making it a local variable in the callback, and try adding console.log calls to ensure that the callback order is what you expect.


You may need to keep a global request counter to ensure that you don't process a response after sending a new request.

For example:

var lastRequest = 0;   //You may want to put this in a namespace or closure

...

var thisRequest = ++lastRequest;
$.ajax({
    type: "POST",
    url: "/sandbox/graphloader/mock3",
    async: false,
    data: {calInput1:dates[0], calInput2:dates[1]},
    success: function(data){
        if (thisRequest !== lastRequest) return;
        ...
    }});

Do not do this inside a loop body or you'll share the thisRequest variable.
Instead, call a function from the loop body.

查看更多
smile是对你的礼貌
4楼-- · 2019-02-18 16:54

It's freezing because it's not getting a 'success' response and you haven't handled the error. Set an error: function(jqXHR, textStatus, errorThrown){} in you settings to handle the error response. async: false works fine.

查看更多
登录 后发表回答