2012-10-11 33 views
3

我試圖在上傳文件並將其解壓縮時顯示進度百分比。我正在使用ruby-zip解壓縮文件。解壓縮時,我將計數器增加並存儲在數據庫中。我有一個像ajax在後臺發生其他事情時調用

<% form_tag '/unzip', :multipart => true do %> 
    <%= file_field_tag "zipfile", :size => 12 %> 
    <button class="add_button" type="submit" value="Add"> Add </button> 
<% end %> 
<div class="progress"> 
</div> 

形式在unzip行動有一個進行解壓縮並存儲在數據庫中的一切有價值的東西。現在,我想每2秒鐘更新一次.progress div。首先,我試着在單擊按鈕時進行ajax調用,並調用另一個獲取此進度的方法。但是我沒有成功,因爲下面這個簡單的代碼給了我錯誤。

<script> 
$(".add_button").click(function() { 
    $.ajax({ 
    url: "/get_progress", 
    method: "POST" 
    }) 
}) 
</script> 

在get_progress方法,我只是拿出價值從數據庫中像

def get_progress 
    @progress = Progress.last.value 
    respond_to do |format| 
    format.js 
    end 
end 

對於簡單的檢查目的,我只是做console.log("rendered")get_progress.js.erb。但是它永遠不會被調用,因爲它之前有錯誤信息。但是,我檢查並且ajax呼叫向get_progress發出請求。

但問題是,我得到錯誤xhr.send((s.hasContent && s.data) || null)在jquery1.6.3行號7948.我想我得到這個錯誤,因爲該網頁的Ajax調用時重定向別的地方,還有另一個要求回事,而我進行調用,因爲很明顯,當表單被提交時我有另一個操作。

當我打印出Ajax調用錯誤這樣做:

error:function(xmlHTTPRequest, textStatus, errorThrown){ 
    console.log(xmlHTTPRequest); 
} 

我得到這個:

Object {readyState = 0 ,status = 0 ,statusText = "error" } 

我想我的問題是,類似這樣的question。但是,這裏提供的答案並沒有解決我的問題。

有什麼辦法可以解決這個問題嗎?我希望問題很清楚!

回答

1

當我將ajax調用從post更改爲get時,這似乎適用於我。

查看:

Progress: 
<div id="progress"> 
</div> 

<br /> 

<button class="add_button" type="submit" value="Add"> Add </button> 
<script> 
$(".add_button").click(function() { 
    $.ajax({ 
    url: "/get_progress", 
    method: "get", 
    dataType: "script" 
    }) 
}) 
</script> 

控制器:

def get_progress 
    @progress = Progress.last.value 
    respond_to do |format| 
    format.js 
    end 
end 

get_progress.js.erb:

$("#progress").text("<%= @progress.to_s %>"); 

一些明顯的事情來檢查:

  • 您添加了「get」進程的「get_progress」的正確路由
  • JQuery已安裝並正在運行
  • get_progress.js.erb中的代碼是正確的。如果JS和嵌入式導軌邏輯工作不正常,通常它看起來像「什麼都沒有發生」。從上面簡單的事情開始......

P.S.要在循環中運行它:

function updateProgress() { 
     $.ajax({ 
     url: "/get_progress", 
     method: "get", 
     dataType: "script" 
     }); 
} 

// Set the function above to run every 2 seconds 
var i = setInterval(updateProgress, 2000); 

而且更新get_progress.js.erb:

$("#progress").text("<%= @progress.to_s %>"); 
var checkprogress = <%= @progress.to_i %>; 
if (checkprogress == 100) { 
    // Stop the function running. Should add clearInterval to error handling of ajax also 
    clearInterval(i); 
} 

編輯

如果之間提交解壓行動和某種衝突檢索進度,我建議您使用remotipart來解壓縮提交異步。然後改變形式解壓到:

<% form_tag '/unzip', :html => { :multipart => true }, :remote => true do %> 

<%= remotipart_response do %>添加一個create.js.erb文件按照remotipart自述。我仍然建議get_progress ajax調用是一個get方法。

+0

ajax調用本身工作正常。問題是什麼時候Ajax調用發生了什麼事情。就像我所說的那樣,當進度被取消時,進度表也會得到更新。這部分是由表單的動作解壓縮方法完成的! –

+1

@SadikshaGautam然後我會建議解壓縮提交是異步的 - 請參閱編輯的答案。 – mccannf

+0

@SadikshaGautam爲你做了這項工作?你需要更多的信息嗎? – mccannf

相關問題