简体   繁体   中英

How does code execution work in regards to the jQuery ajax call?

My understanding about javascript has always been that code executes sequentially, so the next line isn't executed until the one above it executes.

I have something like the following that I was trying to use to try and save a series of question one at a time.

    for(var i = 1; i <= assessment_question_count; i++)
    {
        if(valid)
        {
            var sort = i;
            $.ajax(
            {
                type: "POST",
                url: '/assessmentquestion/create',
                data: 'assessment_id=' + assessment[1] + '&question_text=' + $('#assessment_question_text_' + sort).val() + '&assessment_question_type_id=' + 
                    $('assessment_question_type_' + sort).val() + '&sort_order=' + i,
                success: function (str) 
                {
                    var result = str.split('|');
                    if (result[0] == 'success') 
                    {
                        var message = '<br />Question saved ';
                        update_display_message(message);
                    }
                    else if(result[0] == 'fail')
                    {
                        valid = false;
                        var message = '<br />Error saving question ';
                    }
                    else 
                    {
                        valid = false;
                        var message = '<br />Error saving question ';
                    }
                }
            });
        }
    }

The problem I'm running into is it seems to go onto the next loop as soon as it makes the ajax call, not waiting for it to complete. Is there a way to modify this so it doesn't try the next question until the previous updates?

Edit: I'm thinking maybe stick it in a recursive method that keeps calling itself until it's done.

By default, ajax works asynchronously .

Set async to false to prevent this.

$.ajax(
            {
                type: "POST",
                url: '/assessmentquestion/create',
                async: false,
                etc...

XMLHttpRequests are async by default in the browser. If you REALLY want to, you can make it synchronous by setting async: false in your ajax options, but this isn't advisable as this will lock up the entire UI - pretty much nothing else is going to happen until that request comes back.

Often times it is best to reduce the number of round trips to the server to complete a task. In your case, sending X number of requests while waiting for a response before completion is likely a bad user experience.

In my opinion it would be best to seralize your data in to an array or JSON and then post the collection set as a single data entity, do validation and send back a JSON response with all of the validation errors and/or messaging neeed.

While this may add to the client side coding you'll need to do it will provide for a much more reliable UI and a better user experience.

Yes. By calling $.ajax() , you are setting a callback ( success ) which will be called when the data comes back. No need to wait in between; you'll be interrupted, so it goes to the next loop.

问题是ajax调用是异步发生的,因此将其名称添加到您的ajax调用中:

async : false 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM