簡體   English   中英

使用Rails提交Ajax表單

[英]Submit Ajax Form using Rails

在我的Rails應用中,我想在用戶上傳圖像時更新模型。 選擇圖像后,圖像會立即顯示在頁面上,但是圖像應該作為AJAX調用在后台上傳。 換句話說,應提交表單, 而無需用戶單擊提交按鈕-選擇文件后,表單應自動提交。

在我當前的實現中,新上載的圖像會顯示在頁面上,但是它會觸發HTML更新,即使表單上的remote設置為true也會導致頁面刷新。 如何確保該表單作為AJAX請求提交?

(我遵循此頁面上的示例: 以ajax方式(使用jQuery)在rails 3中提交表單

 <%= form_for [@collection], :html => {:id => "collection_avatar_form" }, :remote => true do |f| %>
      <div id="uploadImageWrapper" title="Edit Avatar">
         <%= image_tag(@collection.image_url(:thumb), :class=>"img-rounded") %>
         <div id="editAvatarIcon"><icon class="fa fa-pencil"></icon></div>
         <%= f.file_field :image %>
     </div>
<% end %>

創建以下HTML的代碼:

<form accept-charset="UTF-8" action="/collections/introduction-to-product-design--3" class="edit_collection" data-remote="true" enctype="multipart/form-data" id="collection_avatar_form" method="post">

Javascript:

  $('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;        
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }
    $('#collection_avatar_form').trigger('submit.rails');
  });

你應該用

$.post('yourURL', this.form.serialize())

代替

this.form.submit();

這就是最終對我有用的東西(其中#collection_image是file_field的ID,而#collection_image_form是表單)

$('#collection_image').change(function(){
    var F = this.files;

    var reader = new FileReader();
    var image  = new Image();
    reader.readAsDataURL(F[0]);  
    reader.onload = function(_file){
        image.src    = _file.target.result;              
        image.onload = function() {
            $('#collectionAvatar').find('img').attr('src', this.src);
        };
    }

    $.ajax({
          type: "POST",
          url: $('#collection_avatar_form').attr('action'), 
          data: new FormData($('#collection_avatar_form')[0]),
          processData: false,
          contentType: false,          
          dataType: "JSON" 
      }).success(function(json){
          console.log("success", json);
    });

  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM