Rails Ajaxノート

5371 ワード

ujs使用
インストール
Gemfileではアプリケーションにgem 'jquery-rails'が使用する.jsにこの2行を追加します.
//= require jquery
//= require jquery_ujs

ケース: :delete, :data => { :confirm => " " } %>
  • :data => { :confirm => " " }という属性を使用してdata-confirm=「OKをクリックして続行」というHTMLコードを追加し、ujsはポップアップボックスに処理します.
  • :method => :deleteプロパティは、私たちの接続にdata-method=「delete」プロパティを追加します.これにより、ujsはこのクリック動作を送信し、delete要求削除リソースを送信します.これはRESTの要求に合致します.
  • { :"disable-with" => " ..." } %> aラベルにdata-disable-withプロパティを追加し、クリックすると無効にし、文字情報を提示します.これにより、ユーザーがフォームを複数回コミットしたり、リンク操作を繰り返したりすることを防止できます.
  • def create
      sleep 10
      @product = Product.new(product_params)
    

    ページ操作の更新なし
    ajaxのリクエストを生成し、フォームにパラメータremote: trueを追加してフォームにremoteを追加すると、ujsは非同期リクエストを送信することを知る.

    ,ujs jQuery.ajax() , text/javascript ,Rails , action , : (save) , (view) js

    controller

    respond_to do |format|
      if @product.save
        format.html {...}
        format.js
      else
        format.html {...}
        format.js
      end
    end
    

    create.js.erb しいファイルapp/views/products/create.js.Erb、ここで、 しく した を、 のリストに します.

    $('#productsTable').prepend('');
    $('#productFormModal').modal('hide');
    
    escape_javascript j renderからのlinkは の を します.
    app/views/products/_product.html.erb
    
      
      
      
         t("helpers.links.edit")), edit_product_path(product), :class => 'btn btn-default btn-xs editProductLink', remote: true, data: { type: 'json' } %>
         t("helpers.links.destroy")), product,
          :remote => true,
          :method => :delete,
          :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
          :class => 'btn btn-xs btn-danger' %>
      
    
    

    jsonデータのページ t("helpers.links.edit")), edit_product_path(product), remote: true, data: { type: 'json' }, :class => 'btn btn-primary btn-xs editProductLink' %> remote: true, data: { type: 'json' }とclass .editProductLink
    しいファイル、app/assets/javascripts/products.coffee
    jQuery ->
      $(".editProductLink")
        .on "ajax:success", (e, data, status, xhr) ->
          $('#alert-content').hide() [1]
          $('#editProductFormModal').modal('show') [2]
          $('#editProductName').val(data['name']) [3]
          $('#editProductDescription').val(data['description']) [3]
          $('#editProductPrice').val(data['price']) [3]
          $("#editProductForm").attr('action', '/products/'+data['id']) [4]
    

    [3] した を [4]フォームの を する
    controller
    def edit
      respond_to do |format
        format.html
        format.json { render json: @product, status: :ok, location: @product } [1]
      end
    end
    

    [1]editメソッドに、 たちの に されるjsonフォーマット .
    def update
      respond_to do |format|
        if @product.update(product_params)
          format.html { redirect_to @product, notice: 'Product was successfully updated.' }
          format.json [1]
        else
          format.html { render :edit }
          format.json { render json: @product.errors.full_messages.join(', '), status: :error } [2]
        end
      end
    end
    

    [1]updateメソッドは、jsonの を け れることができます.[2]updateが した 、 の をクライアントに える があります.これもjson です.
      $("#editProductForm")
        .on "ajax:success", (e, data, status, xhr) ->
          $('#editProductFormModal').modal('hide')
          $('#product_'+data['id']+'_name').html(  data['name'] )
          $('#product_'+data['id']+'_price').html(  data['price'] )
        .on "ajax:error", (e, xhr, status, error) ->
          $('#alert-content').show()
          $('#alert-content #msg').html( xhr.responseText )
    
    

    ケース true, 'data-type' => 'script', 'data-url' => url_for(controller: 'settings', action: 'fetch_district_detail', format: 'js') } %>「script」: テキストJavaScriptコードを します. は にキャッシュされません.「cache」パラメータが されていない り. :リモートリクエスト ( じドメインではない)に、すべてのPOSTリクエストがGETリクエストに します.(DOMのscriptタグでロードされるので)http://www.w3school.com.cn/jquery/ajax_ajax.asp
    controller
    def show
      @subdistrict = {}
    end
    def fetch_district_detail
      @subdistrict = Subdistrict.where(district_id: params[:instructor][:district])
    end
    

    fetch_district_detail.js.erb
    $("#sub-district").html("");
    
    

    も なjquery ajaxの き には
    url: を する 、つまり を するserverのURL method:GET、POST、DELETE、PATCHなどの を するタイプ: にserverに する dataType:serverに を する フォーマットsuccess: に するfunction、functionはserverに する を ち む