1

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

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

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

在我调用表单提交的函数中,我有以下代码片段:

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 数据的其余部分后弄清楚如何处理它们。

4

1 回答 1

2

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

$("#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 之类的东西来为用户提供良好的等待体验,直到完成为止。

于 2013-05-12T20:33:34.637 回答