.modal-body .container-fluid .row .col-md-12 1.下載模板文件 = link_to '模板文件' .row .col-md-12 = form_tag '', :id => "my-form" do .input-group %span.input-group-btn %button#fake-file-button-browse.btn.btn-default{:type => "button"} %span.glyphicon.glyphicon-file = file_field_tag :category_file, :id => "files-input-upload", :style => "display:none" %input#fake-file-input-name.form-control{:disabled => "disabled", :type => "text"}/ %span.input-group-btn %button#fake-file-button-upload.btn.btn-default{:disabled => "disabled", :type => "button"} %span.glyphicon.glyphicon-upload
使用formdata獲得完整表單,將formdata做爲data值傳遞給後臺,就如同點擊submit提交數據同樣。注意此處的url和type對應的值不能直接寫到表單裏面,而應寫在ajax的配置參數中ajax
$('#fake-file-button-upload').click(function() { var form = new FormData(document.getElementById('my-form')); $.ajax({ url: "/tax_categories/get_category", type: "POST", data: form, dataType: "json", processData: false, // 不處理數據 contentType: false, //要加 success: function(data) { console.log(data); if (data.result == "error") { alert(data.result); } else { console.log("save success"); window.location = "/tax_categories" } } }); });
使用creek解析xmljson
require 'creek'
def get_category flag = true begin file = params[:category_file] creek = Creek::Book.new file.path sheet = creek.sheets[0] sheet.rows.each do |row| puts row end rescue flag = false end if flag respond_to do |f| f.json { render :json => {:result => "success"}.to_json } end else respond_to do |f| f.json { render :json => {:result => "error"}.to_json } end end end
此處還有個比較二的問題,是發生了302重定向,剛開始controller中的代碼是以下,在解析成功後想直接跳轉,但是在ajax的請求下,產生的是302重定向,在瀏覽器中並不會顯示跳轉。因此採用在js中location定位到新的頁面瀏覽器
if flag redirect_to tax_categories_url else respond_to do |f| f.json { render :json => {:result => "error"}.to_json } end end