猿问

比脚本函数晚于运行的 Ajax 操作

我正在构建一个django项目,这是一个网站将表单发送到服务器,服务器使用表单刚刚注册的查询集和消息字符串“创建新事件成功”进行响应。


这是它的代码:

是另一个javascript函数,它将服务器刚刚收到的查询集显示为“侧边栏”div。之后,by 将消息追加到结果上方。listeventdocument.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );


脚本


function makeEvent(event){

            event.preventDefault();

            var year = event.target.childNodes[3].children[0].value.slice(0,4);

            var month = event.target.childNodes[3].children[0].value.slice(5,7);

            var day = event.target.childNodes[3].children[0].value.slice(8,10);

            var form = $("#makeEventForm");

            $.ajax({

                type: form.attr('method'),

                url: form.attr('action'),

                data: form.serialize(),

                success: function(response){

                    console.log(response);                   

                    listevent(year, month, day);

                    document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );

                },

                error: function(request,status,error){

                    if (request.status == 599) {

                        listevent(year, month, day);

                        document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Error : time overlaps with another event" );

                    } else {

                        alert("code:"+request.status+"\n"+"message:"+status+"\n"+"error:"+error);

                    }

                },

            });

        }

问题是,当这个函数运行并且ajax操作成功完成时,成功函数()的第二行似乎比第三行晚运行。因此,不会显示“成功创建新事件”,因为函数会覆盖 div 中的所有内容。makeEventlistevent(year, month, day);listeventsidebar


所以我尝试在第三行上使用,但似乎一直都不起作用。如果我将时间值设置得足够大,它就会起作用,但它看起来很糟糕。setTimeout


所以,我的问题是:

1.成功函数的第二行看起来比第三行晚运行,对吗?

2. 如果是这样,到第三线运行后第二行结束运行,我该怎么办?


喵喔喔
浏览 94回答 2
2回答

桃花长相依

这是显而易见的,因为内部您正在调用Async AJAX,因此它将并行运行,并且显然将比脚本响应晚于脚本响应,因此脚本将首先执行,然后ajax响应将出现并生效。listevent()要修复,您可以使用的是ajax方法。这将强制脚本等待 ajax 返回响应。但这不是一个好的做法。async:falsefunction listevent(year, month, day){&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "{% url 'listevent' %}",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; async:false, // added&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(response){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('year', year);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('month', month);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('day', day);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; events = JSON.parse(response.events)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(events.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str += "No events currently."&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").html(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var btn = $("<button></button>").html("New event");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; btn.click(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; makeEventClick(day);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").append(btn);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function(request,status,error){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(error);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }因此,作为一种良好做法,您可以将下一行移动到 .listevent()function listevent(year, month, day){&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "{% url 'listevent' %}",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: {'year':year, 'month':month, 'day':day, 'csrfmiddlewaretoken': '{{ csrf_token }}'},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(response){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('year', year);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('month', month);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").attr('day', day);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; events = JSON.parse(response.events)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var str = "<h4>"+year+"/"+month+"/"+day+"</h4><br>"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(events.length > 0){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;events.forEach(event => str += (event['fields']['start_time']+" - "+event['fields']['title']+"<br>"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; str += "No events currently."&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").html(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var btn = $("<button></button>").html("New event");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; btn.click(function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; makeEventClick(day);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $("#sidebar").append(btn);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." ); // Added&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function(request,status,error){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(error);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }

HUH函数

似乎是 AJAX 异步工作的情况。 已成功运行,但由于它的 AJAX 操作,代码不会等到收到响应,这是成功/失败回调的剩余部分。listevent调用和AJAX调用开始,而不是等待它完成,它移动到下一行,即listeventdocument.getElementById("sidebar").insertAdjacentHTML( 'afterbegin', "Create new event successful." );因此,我的建议是在成功回调结束时移动此 n 侧。listevent
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答