开发者

Rails Button, remote_function. Possible without Ajax?

I want to create a very simple search partial. It has a text box, to query, and search db. Can I create a remote_function call without using AJAX or JS? Can I keep it entirely "Rails-ee"?

<%= text_field_tag "search_term",'', :size 开发者_如何学运维=> 10 %>
<%= button "search", :onclick => remote_function( :url => {:action => :fill_in_lots }, 
                                                  :with => "search_term" ) %>


This isn't a problem, you need to use a technique called formal link. Instead of button you put a from with submit button. Below is a code of helper I use for this:

def formal_link_to(*args, &block)
    options = html_options = name = nil
    if block_given?
      options = args.first
      html_options = args.second
      name = capture(&block)
    else
      name         = args.first
      options      = args.second || {}
      html_options = args.third
    end

    method = html_options.delete(:method) || "POST"
    method = method.to_s.upcase
    url = url_for(options)

    html = "<form class=\"formal-link\" action=\"#{url}\" method=\"post\">"
    html += "<input type=\"hidden\" value=\"#{form_authenticity_token}\" name=\"authenticity_token\" />" 
    html += "<input type=\"hidden\" value=\"#{method}\" name=\"_method\" />" 
    html += link_to(name, "#", html_options)
    html += "</form>"

    if block_given?
      concat(html)
    else
      return html
    end
  end

You use this helper like a normal link_to, but you can pass extra options :method in second hash. Example:

<%= formal_link_to "Fill in lots", { :action => "fill_in_lots" }, { :method => :post } -%>

Remarks: 1. This of course will make the full page reload, but it is inevitable without using JavaScript. 2. I assumed action fill_in_lots is exposed to POST request. In case of GET you can use normal link_to helper.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜