2013-05-12 68 views
0

我有一个非常复杂的形式,其中包含多个选项卡。每个选项卡包含一个独特的Plupload实例(用于上传多个图像)。该表格允许用户上传医学图像'病例',其中每个病例由多个成像'研究'(例如CT扫描)组成,并且每个研究包含多个图像。我需要帮助找到一个替代同步jQuery ajax

当用户点击“提交”按钮,我拦截使用jQuery的点击,因为我需要做到以下几点:

  1. 检查必填字段中输入[易]
  2. 得到一个来自我的服务器的唯一ID号码。这个ID号是每个Plupload实例需要知道要上传到哪个目录的。

在我的功能呼吁表单提交,我有以下的代码片段:

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脚本知道如何处理表单的剩余部分。

+0

您需要使所有内容异步,然后重新提交表单。 – SLaks 2013-05-12 20:24:40

+0

为什么选择投票? – Garry 2013-05-13 21:46:00

回答

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(); 
     } 

    }); 
}); 

长话短说,保持“处理问题或提交表单”回调的内至$不用彷徨通话将主要导致脚本“暂停”,直到它得到的数据备份。然后,您可以使用类似spin.js的内容为用户提供良好的等待体验,直至完成。

+0

不要紧,但可能需要将'event.preventDefault();'作为处理程序的第一行。这样,如果在主代码中抛出任何错误,它将不会被跳过 – Ian 2013-05-12 20:35:49

+0

好点。 [4个以上的人物去啊,我们去] – Stephen 2013-05-12 20:38:52

+0

谢谢你这么多斯蒂芬。完美的作品。如果只有5个小时前我能想出我自己! – Garry 2013-05-12 20:53:48