简体   繁体   English

关于jQuery ajax调用,代码执行如何工作?

[英]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. 我对javascript的理解一直是代码是按顺序执行的,因此下一行直到上一行执行后才会执行。

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. 我遇到的问题是,它发出ajax调用后似乎会立即进入下一个循环,而不是等待它完成。 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 . 默认情况下, ajax是异步工作的

Set async to false to prevent this. async设置为false可以防止这种情况。

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

XMLHttpRequests are async by default in the browser. 默认情况下,XMLHttpRequest在浏览器中是异步的。 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. 如果您确实想要,可以通过在ajax选项中设置async: false使其同步,但这是不可取的,因为这会锁定整个UI-在该请求返回之前,几乎没有其他事情发生。

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. 在您的情况下,在等待响应完成之前发送X个请求数量可能会带来糟糕的用户体验。

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. 在我看来,最好将您的数据序列化为数组或JSON,然后将集合集作为单个数据实体发布,进行验证并以所有验证错误和/或带有消息传递的方式发送回JSON响应。

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. 尽管这可能会增加客户端编码,但是您将需要这样做,它将提供更加可靠的UI和更好的用户体验。

Yes. 是。 By calling $.ajax() , you are setting a callback ( success ) which will be called when the data comes back. 通过调用$.ajax() ,您可以设置一个回调( success ),该回调将在数据返回时调用。 No need to wait in between; 无需在两者之间等待; you'll be interrupted, so it goes to the next loop. 您会被打断,因此转到下一个循环。

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

async : false 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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