1

I have a question regarding using getJson.

I had a getJson call and I couldn't figure out why it didn't do what is was supposed to do. I then put an alert after the getJson and found out that the alert was getting executed before the getJson.

I then figured the only way to solve this would be to use $.ajax with async false as follows

     $.ajax({
            url: url,
            dataType: 'json',
            async: false,
            success: function (data) {
                if (data == true) {                         
                    alert("Cannot continue.")
                    returnval = false;
                }
            }
        });

Just wondering if there is any other way to solve this issue to where I need the json through ajax call to execute first without using async false. Note that I am using MVC C# the the above code is in my view.

4

1 回答 1

0

It's simple - remove the async: false. You need to place code that will run after your calls in the success block, as you have done. If you have a large amount of code to execute, it is possible to place it into its own function:

var doThisOnResult = function(data) {
  alert('Data is here.');
};

Then in your $.ajax call, do

success: doThisOnResult

Note that you don't want to use parens on that line, since you are passing your function as a variable instead of calling it.

于 2012-10-19T05:09:27.683 回答