我需要帮助找到同步jQuery ajax的替代方案

我有一个非常复杂的表单,其中包含多个选项卡。 每个选项卡都包含一个唯一的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; } 

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

我的问题是双重的:

  1. 有没有办法阻止脚本,直到我得到所需的case_id?
  2. 如果没有,任何想法如何改变我的逻辑来解决这个问题?

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

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

 $("#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这样的东西来给用户一个良好的等待体验,直到它完成。