【问题标题】:I need help finding an alternative to synchronous jQuery ajax我需要帮助找到同步 jQuery ajax 的替代方法
【发布时间】:2013-05-12 20:23:18
【问题描述】:

我有一个非常复杂的表单,其中包含多个选项卡。每个选项卡都包含一个唯一的 Plupload 实例(用于上传多个图像)。该表格允许用户上传医学图像“病例”,其中每个病例由多个成像“研究”(例如 CT 扫描)组成,每个研究包含多个图像。

当用户点击“提交”按钮时,我使用 jQuery 拦截点击,因为我需要执行以下操作:

  1. 检查必填字段是否输入[easy]
  2. 从我的服务器获取一个唯一的 ID 号。每个 Plupload 实例都需要此 ID 号才能知道要上传到哪个目录。

在提交表单时调用的函数中,我有以下代码 sn-p:

var case_id;

// Code to check the required fields are entered
....

// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
    case_id = data;
});

// do something with case_id and other things. MUST happen after the ajax call
....

// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
    return false;
}

按照我当前的逻辑,我需要暂停脚本直到它获得 case_id。这在 jQuery 1.8 之前是可能的,但 $.ajax() async : false 属性已被弃用。

我的问题有两个:

  1. 有没有办法在我获得所需的 case_id 之前暂停脚本?
  2. 如果没有,知道如何更改我的逻辑来解决这个问题吗?

您可能想知道为什么 case_id 如此重要。 plupload 实例在表单提交之前进行上传,它们需要一个目录来上传。我希望上传的图像进入我的服务器上名为 case_id 的文件夹。这将让服务器上的 PHP 脚本在获取表单 POST 数据的其余部分后弄清楚如何处理它们。

【问题讨论】:

  • 你需要让一切异步,然后重新提交表单。

标签: javascript jquery logic


【解决方案1】:

这是一个非常常见的“问题”,可以通过适当地使用回调很容易地解决。

$("#submitButton").click(function (event) {
    event.preventDefault(); //Don't submit the form, we'll submit it manually.

    var case_id;

    // Code to check the required fields are entered
    ....

    // Get the case id number from the server
    $.get('ajax/unique-case-id').done(function(data){
        case_id = data;

        // do something with case_id and other things. MUST happen after the ajax call
        ....

        // if there was a problem uploading the images, stop the form from submitting
        if (problem_occured) {
            alert("something went wrong");
        } else {
            $("#referenceToTheForm").submit();
        }

    });
});

长话短说,将“处理问题或提交表单”保留在 $.get 调用的回调中将导致脚本“暂停”,直到它取回数据。然后,您可以使用 spin.js 之类的东西为用户提供良好的等待体验,直到完成为止。

【讨论】:

  • 没关系,但您可能希望将event.preventDefault(); 作为处理程序的第一行。这样,如果在主代码中抛出任何错误,将不会被跳过
  • 非常感谢斯蒂芬。完美运行。要是我能在 5 小时前自己弄清楚就好了!
  • 没问题..当您尝试等待多个服务响应时,它会变得更有趣:)
猜你喜欢
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多