在rails中使用jquery实现Ajax
下面通过一个实例来讲解如何在Rails用jquery实现Ajax式的添加和删除操作.
我的环境:
ruby187,rails 222,jquery1.3.2, jquery.form.js

首先新建rails应用
rails app -d mysql
新建数据库app_development
script/generate model product name:string
script/generate controller products index
rake db:migrate


把jquery.js和jquery.form.js放到public/javascripts目录下

编辑app/app/views/layouts/application.html.erb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>Application</title>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
      <title>index</title>
      <%= javascript_include_tag "jquery" %>
      <%= javascript_include_tag "jquery.form" %>
      <%= javascript_include_tag "application" %>
    
</head>

<body>

    <%= yield %>

</body>
</html>

在products_controller.rb中定义下面几个action:


class ProductsController < ApplicationController
  def index
      @products = Product.find(:all)
  end

  def create
    if Product.create(params[:product]).valid?
      @products = Product.find(:all)
      render :partial => "products_list"
    else
      render :text => "something  wrong", :status => "500"
    end
  end

  def delete
    Product.destroy(params[:id])
    @products = Product.find(:all)
    render :text => ""
  end
 
end


编辑app/app/views/products/index.html.erb
<% form_for :product, :html=>{:method=>"post",:id=>"create-product"}, :url=>{:controller=>"products", :action=>"create"} do |f|%>
<label>Product Name:<%= f.text_field :name %></label>
<%= submit_tag "submit" %>
<% end %>

<div id="products-list">
  <%= render :partial => 'products_list'%>
</div>


编辑app/app/views/products/_products_list.erb
<% unless @products.empty? %>
<table>
    <tr>
        <th><b>Product Name</b></th>
    </tr>
    <% @products.each do |product| %>
    <tr>
        <td>
        <%= product.name%>
        </td>
        <td><%= link_to "Delete", {:controller=>"products", :action=>"delete",:id=>product}, :class=>"delete"%></td>
        <td>Edit</td>
    </tr>
    <% end %>
</table>
<% end %>


编辑public/javascripts/application.js
DeleteProduct()是用jquery实现的ajax方式.
CreateProduct()用到了jquery.formAjax提交方式

$(document).ready(function() {
    function DeleteProduct() { //定义删除函数
      $('#products-list a.delete').bind('click', function() {//将delete链接与click绑定
        var deleteLink = $(this)  //将这个链接的dom赋值给deleteLink变量
        $.ajax({       //Ajax函数
          type: 'delete',   //定义http方法
          url: deleteLink.attr('href'),    //请求的URL
          success: function(){deleteLink.parent().parent().remove()} //请求成功之后的动作
        })
        return false//阻止普通的提交方式和页面导航

      })
    }

    function CreateProduct() {//添加product函数
      $('#create-product').submit(function() {//点击submit的函数
        $(this).ajaxSubmit({//点击submit发起ajax请求
          target: '#products-list',  //目标是对id=product0list的dom进行局部更新
          clearForm: true,
          success: DeleteProduct, 
          error: displayError//发生错误,譬如validate?为false时
        })
        return false
      })
    }

    function displayError(request, errorType) {
      var msg = '<div class="error">'+request.responseText+'(click to close)</div>'
      $('#products-list').append(msg)
      $('.error').click(function(){$(this).hide()})
    }

    $(function() {
      DeleteProduct()
      CreateProduct()
    })
   
});
jquery.form.js的更多内容参阅API

现在启动服务 script/server
就可以看到用Ajax实现的添加和删除了.