gpt4 book ai didi

javascript - JavaScript 调用约定有问题

转载 作者:行者123 更新时间:2023-11-28 12:45:08 24 4
gpt4 key购买 nike

这是代码的快照:

enter image description here

如果 Line:3 处的函数 testFields 返回 false,则控件将正确转到 Line:21 并返回 false.如果 testFields 返回 true,则控件将转到 Line:4,然后不再继续处理 函数中返回的响应Line:5,控件继续到 Line:21,其中 retVal 仍为 false。也就是说,在函数向函数返回值后检查 Line:6 的条件:

<form method="POST" onsubmit="return validateInput()" />

从逻辑上讲,它应该首先测试 Line:7 处的条件,然后决定 retVal 应该为 true 还是让它为真默认 false,然后应通过 Line:21 返回值。

我的代码在逻辑上有什么问题?

最佳答案

有两种方法。

  1. 您可以发出同步ajax请求。

    var retVal ;
    $.ajax({
    url: youUrl,
    async: false, // required to pause script until request is done
    success: function( ret ) {
    retVal = ret; // ret is invisible outside this callback

    },
    error : function( err ) {
    // your error logic
    }

    });
    //We'll in this line if request is completed and either success or error callback was called.
    return retVal;
  2. 但是如果您不希望脚本被停止。您可以阻止表单中的默认操作,并从回调发送表单,例如:

    $( "form" ).submit( function( e, extra ) { 

    if( !extra )
    $.post(
    url: "script.php",
    data: "yourdata",
    success: function( ) {
    $( "form" ).trigger( "submit", [true] );
    },
    error: function(){}
    );

    // extra parameter will be always undefined until we'll not pass it in an array which will be aplied to listener as next ones arguments - take a look at success callback
    return !!extra // doubled negate operator ensures that extra will be returned as boolean because if you return undefined that means you didn't return anything
    });

以及没有 onsubmit 声明的 html 表单标签:

<form method="POST" />

关于javascript - JavaScript 调用约定有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8665293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com