Rails form_tag remote example

后端 未结 3 1273
轻奢々
轻奢々 2020-12-31 18:55

I have this incredible simple form:

<%= form_tag(\"/portal/search\", method: \'get\', remote: true ) do %>

  <%= label_tag(:query, \'Search for:\')         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-31 19:41

    When you add remote: true jquery-ujs will provide you the ajax request (by default this javascript lib is required in app/assets/javascripts/application.js).

    The ajax call will request a 'text/javascript' response. for that reason your server code should reply with:

    # action
    def search_query
      respond_to do |format|
        format.js { 
          # additional code
        }
      end
    end
    

    If in your view (search_query.js.erb) you provide javascript, it will be executed. That is why everyone is replying you with a $('#my_div_id').html('my html text') suggestion, which when executed will replace your div content with the new HTML.

    If for some reason you want to return a json data structure, then you should provide a different data-type:

    form_tag("/jquery_ujs/search_query", remote: true, 'data-type' => :json) do
      # ....
    end
    

    And you should reply with:

    # action
    def search_query
      respond_to do |format|
        format.json { render json:  @my_object }
      end
    end
    

    And handle the success event:

    
    

    You can also request a html response (in case you want to return a table, for instance), with :'data-type' => :html and format.html { render layout: false }

提交回复
热议问题