How do you make javascript code execute *in order*

后端 未结 9 1196
别那么骄傲
别那么骄傲 2020-11-30 05:49

Okay, so I appreciate that Javascript is not C# or PHP, but I keep coming back to an issue in Javascript - not with JS itself but my use of it.

I have a function:

9条回答
  •  青春惊慌失措
    2020-11-30 06:26

    I thinks all you need to do is have this in your code:

    async: false,
    

    So your Ajax call would look like this:

    jQuery.ajax({
                type: "GET",
                url: "something.html for example",
                dataType: "html",
                async: false,
                context: document.body,
                success: function(response){
    
                    //do stuff here
    
                },
                error: function() {
                    alert("Sorry, The requested property could not be found.");
                }  
            });
    

    Obviously some of this need to change for XML, JSON etc but the async: false, is the main point here which tell the JS engine to wait until the success call have returned (or failed depending) and then carry on. Remember there is a downside to this, and thats that the entire page becomes unresponsive until the ajax returns!!! usually within milliseconds which is not a big deals but COULD take longer.

    Hope this is the right answer and it helps you :)

提交回复
热议问题