【问题标题】:Async request with AJAX使用 AJAX 的异步请求
【发布时间】:2020-05-03 23:37:38
【问题描述】:
$.ajax({
        async:false,
        url: "ajax/stop_billed_reservation_delete.php",
        type: "POST",
        dataType : "json",
        data : { "rid" : <?php echo $_GET['reservationId']; ?> },
        success: function(result){
            console.log(result);
            return result;
        }
    });

我的目标是返回 ajax 响应。但在返回响应脚本运行其他部分之前。我该如何解决这个问题!

ajax 响应应该是 truefalse 所以返回值应该是 truefalse

此脚本用于停止表单提交。 如果返回值为 true,则表单应提交,否则 (false) for 不应提交。

(此代码用于验证表单)

【问题讨论】:

  • 您在stop_billed_reservation_delete.php 文件中获得了rid 值?
  • 在异步调用成功函数中返回值没有意义
  • ajax response should be true or false so return value should be true or false 是的,成功回调返回 true 或 false(请参阅我之前的评论以实现此返回值的无用性)......但 $.ajax 立即返回一些 jQuery 对象,而不是当结果已知
  • This script is used for stop to form submission. if return value is true, form should submit, otherwise (false) for should be not submit. 最终,您不能通过使用异步函数来阻止表单提交 - preventDefault 不能在以后任意调用 - 您需要重新考虑您的代码(始终防止表单提交,如果这个ajax的结果为真,自己执行表单提交......使用$.ajax
  • 我知道...但它需要-...就像您接受的答案一样

标签: javascript php jquery ajax asynchronous


【解决方案1】:

Ajax 默认是异步的,因此它不等待 ajax 响应。 async: false 不起作用,因为它已被弃用。可以在ajax函数的success函数中运行表单提交。

$.ajax({
    url: "ajax/stop_billed_reservation_delete.php",
    type: "POST",
    dataType : "json",
    data : { "rid" : <?php echo $_GET['reservationId']; ?> },
    success: function(result){
        console.log(result);
        if(result){
            submitForm(); //Run the function that will submit the form.
        }
    }
});

function submitForm(){
    //Relevant code for submitting the form.
    . . . . . .
}

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 2010-11-06
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2019-07-21
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多