【发布时间】:2014-07-05 03:15:19
【问题描述】:
我有一个表单,它接受一个 json 文件并 POST 到服务器端进程。这是一个漫长的过程,我想通过多条消息将其进度实时反馈给用户。
我有什么选择?
此过程可能需要 10-15 分钟或更长时间。我不是在寻找答案“AJAX”。不止于此。
这是我得到的表格:
<form method="POST" accept-charset="UTF-8" class="smart-form" id="import-course" enctype="multipart/form-data">
<fieldset>
<div class="row">
<section class="col col-md-12">
<label class="input input-file">
<input class="button" name="import" type="file">
</label>
</section>
</div>
</fieldset>
<footer>
<button class="btn btn-primary" id="submit-import-file" type="button">Save</button>
<a onclick="history.back();" class="btn btn-default">Cancel</a>
</footer>
</form>
这是我的 ajax:
$(document).ready(function(){
$("#submit-import-file").on('click',function(){
console.log('click');
$('#import-course').hide();
var formData = new FormData($('#import-course')[0]);
$.ajax({
url: '{{URL::route("courses.import")}}', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(data){
console.log(data);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
});
function progressHandlingFunction(e){
console.log(e);
}
这是我的服务器端注意的cmets。
$errors = 0;
$file = Input::file('import');
$fileName = $file->getClientOriginalName();
$destinationPath = app_path()."/storage/files/";
$file->move($destinationPath, $fileName);
$course = json_decode(File::get($destinationPath.$fileName));
if(!File::isDirectory($destinationPath.$course->code)){
File::makeDirectory($destinationPath.$course->code,0777,true,true);
//message back directory created
}
foreach($course->file as $file){
if(FileManger->processfile($file)){
//message back $file->name imported
}else{
//message back error importing $file->name
}
}
return "import complete";
所以现在.. 在此过程中,我如何将评论区域发送回用户。不是之后。
【问题讨论】:
-
了解异步性,实现一个简单的 JS 解决方案,享受 - 将是我的建议选项
-
即使使用 AJAX,当您使用 return 时,您也会在过程中的某个时刻收到 1 个响应。这不是我要找的。这些过程最多可能需要 10-15 分钟。
-
我已经使用 AJAX 来发布数据并在流程完成时做出响应。问题是,如果我尝试在进程内的点发回多条消息,ajax 调用将在第一个停止。