简体   繁体   English

嵌套 AJAX 跳过父 function,不会停止服务器响应

[英]Nested AJAX skips parent function, doesn't stop for server response

I've been making a javascript function and it's getting out of my hands.我一直在制作 javascript function,但它已经脱离了我的掌控。

The code is this:代码是这样的:

$(document).on('click', '.submit', function(event) {
    event.preventDefault();
    if ($('.houdini').attr('is') == "magic") {
        var multimediaData = 0;
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });  
        $.ajax({
            url: '/checkhoudini',
            type: 'POST',
            data: $('.houdini').val(),
            cache: false,
            contentType: false,
            processData: false,
        }).done(function(data) {
            if ($(data).has(data.error)) {
                console.log(data.error);
                return; // <--- THIS IS SUPOSSED TO STOP THE WHOLE PARENT FUNCTION
            } else if ($(data).has(data.success)) {
                console.log('yo check');
                multimediaData == data.success;
                return true; // <--- THIS IS SUPOSSED TO RESUME THE PARENT FUNCTION AS IT IS TRUE
            }
        }).fail(function() {
            console.log('gl next time');
        });
    } else {
        console.log('all went down');
    }
    console.log(multimediaData);
    content = multimediaData // <--- THIS FILLS THE CONTENT VARIABLE WITH THE DATA FROM THE SERVER
    console.log(content);
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });   
    $.ajax({
        url: '/okletsdothis',
        type: 'POST',
        data: {
            _token: $('meta[name="csrf-token"]').attr('content'),
            body: content,
            rabbit: $('.rabbit').val(),
        },
    })
    .done(function(data) {
        console.log(data);
        console.log("success");
    })
    .fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });
});

My problem is that, when doing the first AJAX Call (the nested one inside the if statement), the request is sent to the server, but the parent code doesn't wait for the response, and keeps going .我的问题是,在执行第一个 AJAX 调用(if 语句中的嵌套调用)时,请求被发送到服务器,但父代码不等待响应,而是继续执行 After the server responds, its too late, I get the response from the server but the whole parent script is done.服务器响应后,为时已晚,我从服务器得到响应,但整个父脚本已完成。

Result:结果:

在此处输入图像描述

As you can see, JS skips the whole thing, giving undefined to the logs and jumping like parkour.正如你所看到的,JS 跳过了整个事情,给日志提供了 undefined 并且像跑酷一样跳跃。

From lines 146 to 120 to 163 and the code ends there at line 170.从第 146 行到第 120 行到第 163 行,代码在第 170 行结束。

What can I do in my first ajax call so javascript waits for it to receive a response and then keep executing the parent function?在我的第一个 ajax 调用中我能做什么,所以 javascript 等待它收到响应然后继续执行父 function?

Thank you everyone in advance, have a nice day:)提前谢谢大家,祝大家有个愉快的一天:)

I transferred your snippet into the following one and carried out a few changes:我将您的代码段转移到以下代码段并进行了一些更改:

  • the "parent script" parts are now in the .done() callback for your first .ajax() call. “父脚本”部分现在位于第一个.ajax()调用的.done()回调中。

  • I also replaced your backend server address by one that is globally available for testing.我还将您的后端服务器地址替换为全球可用于测试的地址。

Now everything should work as intended.现在一切都应该按预期工作。

 $(document).on('click', '.submit', function(event) { event.preventDefault(); if ($('.houdini').attr('is') == "magic") { var multimediaData = 0; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url: "https://jsonplaceholder.typicode.com/posts", // changed type: 'POST', data: JSON.stringify({success:"my server response"}), // changed cache: false, contentType: false, processData: false, headers: {'Content-type': 'application/json; charset=UTF-8'}// changed }).done(function(data) { console.log("Ajax: "+data.success); if (data.error) { console.log(data.error); return; // <--- THIS IS SUPOSSED TO STOP THE WHOLE PARENT FUNCTION } else if (data.success) { // changed console.log('yo check'); multimediaData == data.success; console.log("here we go..."); // $.ajaxSetup({ headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')} }); $.ajax({ url: 'https://jsonplaceholder.typicode.com/users', type: 'POST', data: JSON.stringify({_token: "some obscure token", body: content, rabbit: "Peter Rabbit" }), // changed headers: {'Content-type': 'application/json; charset=UTF-8'}// changed }).done(function(data) { console.log(data); console.log("success"); }).fail(function() { console.log("error"); }).always(function() { console.log("complete"); }); return true; // <--- THIS IS SUPOSSED TO RESUME THE PARENT FUNCTION AS IT IS TRUE } }).fail(function() { console.log('gl next time'); }); } else { console.log('all went down'); } console.log("This will always be 0:"+ multimediaData); content = multimediaData // <--- THIS FILLS THE CONTENT VARIABLE WITH THE DATA FROM THE SERVER console.log("and so will this: "+content); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="houdini" is="magic"></div> <button class="submit">go</button>

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

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