如何使用ENTER键从textarea提交AJAX表单?

bri*_*lah 5 ajax jquery ruby-on-rails

我正在开发一个Ruby On Rails 2.3.8应用程序,我想知道如何remote_form_for在用户按下textarea中的ENTER键时提交表单.

这是表单代码:

  <% remote_form_for :post, PostComment.new, :url => save_outside_comment_path(post_id), :html => { :method => :put} do |f| %>
     <%= f.text_area :comment, :rows => 1, :id => "txtOutsideComment_#{post_id}", :class => "new-reply-text" %>
  <% end %>
Run Code Online (Sandbox Code Playgroud)

这是执行提交的jQuery函数,但不是AJAX:

jQuery('.new-reply-text').keypress(function(e) {
    if (e.keyCode == 13 && !e.shiftKey) {
        e.preventDefault();
        this.form.submit();
    }
});
Run Code Online (Sandbox Code Playgroud)

我已经从我的控制器进行了页面更新,我是否不想指定任何语法,例如success:来自这个jQuery函数.我只是想让它提交remote_form_for使用AJAX.

Bro*_*omb 6

我想你问的是如何做一个AJAX请求而不是整页提交.如果是这样

jQuery('.new-reply-text').keypress(function(e) {
  if (e.keyCode == 13 && !e.shiftKey) {
    e.preventDefault();
    jQuery.ajax({
      url: "/my/URL",
      data: jQuery(this).form.serialize(),
      success: function(){},
      dataType: "json"
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

如果使用.get http://api.jquery.com/jQuery.get/,可以保存一些参数.

或.post http://api.jquery.com/jQuery.post/

哪个是.ajax的包装 http://api.jquery.com/jQuery.ajax/

我不是一个铁杆人,所以你需要更新第一个jQuery对象的类/ id才能找到 remote_form_for