jquery - Rails - 有什么关于在 jquery 中通过 json 提交表单的好例子吗?

标签 jquery ruby-on-rails json

我想使用 json 将一些 ajax 功能添加到我的 Rails 应用程序中。 我想做的只是创建一个接受数据输入的表单。 提交表单后,我想获取 json 格式的响应 更新屏幕而不重新呈现表单。

当我浏览网站时,我还没有找到解释这个概念的网站 全面。

您能否向我指出任何可以教我逐步实现预期结果的在线资源或书籍?

最佳答案

这是一个非常简单的概念:

  1. 使用表单助手(假设为 Rails 3)设置 :remote => true 选项。
  2. 确保您的布局上有适当的 jQuery UJS/Rails.js 文件。它将自动锁定助手在表单上生成的 data-remote 属性,并通过 AJAX 提交该表单。
  3. 修改您的 Controller 操作以返回 JSON(见下文)。
  4. 使用 JS 中提供的回调/ Hook 来处理响应(见下文)。

示例:

# app/controllers/foo_controller.rb
def create
  @foo = Foo.new(params[:foo])
  if @foo.save 
    respond_to do |format|
      format.html
      format.json { render :json => @foo }
    end
  else
    respond_to do |format|
      format.html { render :action => :new }
      format.json { render :json => { :errors => @foo.errors } }
    end
  end
end

# app/assets/javascripts/application.js.coffee
$(document).on 'ajax:success', 'form[data-remote]', (xhr, data, status) ->
  # do something with `data`, which is a JS object from your JSON response
  # console.log data

关于jquery - Rails - 有什么关于在 jquery 中通过 json 提交表单的好例子吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9746999/

相关文章:

jquery - rails : Why a single click doesn't work for an anchor created using Sidr jQuery library?

ruby-on-rails - Rails Gmail gem : Get correct address of sender and message body

ruby-on-rails - 如何建立典型的用户HABTM角色关系

javascript - 浏览器可以对 XSS jquery.getJSON() 请求 header 中指定的 Set-Cookie 使用react吗?

jquery - 如何动态地将数据从div正确复制到新窗口

ruby-on-rails - 如何配置 nginx 以在 SubURI 上提供 gitlabhq

php - mysql 数组语法可能需要连接?

python - 如何使用 Python 将 CSV 转换为 JSON?

java - 从网站获取数据到 Google Glass

javascript - 是否可以将处理程序绑定(bind)到 jQuery 效果?