Jester: JavaScript Client for REST

Jester: JavaScriptian REST介绍了Jester这个JavaScript库,它基于Prototype,用来做RubyonRails的RESTful
Web Service的JavaScript客户端,而且api基本模仿了ActiveResource,所以用起来很简单。

服务端:
class UsersController < ApplicationController
  # GET /users.xml
  def index
    @users = User.find(:all)
    respond_to do |format|
      format.xml  { render :xml => @users.to_xml(:include => :posts) }
    end
  end

  # GET /users/1.xml
  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.xml  { render :xml => @user.to_xml(:include => :posts) }
    end
  end
  
  # POST /users.xml
  def create
    @user = User.new(params[:user])
    respond_to do |format|
      if @user.save
        format.xml  { head :created, :location => user_url(@user) }
      else
        format.xml  { render :xml => @user.errors.to_xml }
      end
    end
  end

  # PUT /users/1.xml
  def update
    @user = User.find(params[:id])
    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.xml  { head :ok }
      else
        format.xml  { render :xml => @user.errors.to_xml }
      end
    end
  end

  # DELETE /users/1.xml
  def destroy
    @user = User.find(params[:id])
    @user.destroy
    respond_to do |format|
      format.xml  { head :ok }
    end
  end
end


客户端:
>>> Base.model("User")
>>> eric = User.find(1)
GET http://localhost:3000/users/1.xml
>>> eric.attributes
["active", "email", "id", "name"]

>>> chad = User.build({email: "[email protected]", name: "Chad Pytel"})
>>> chad.save()
POST http://localhost:3000/users.xml

>>> jared = User.build({name: "", email: ""})
>>> jared.save()
POST http://localhost:3000/users.xml
>>> jared.errors
["Name can't be blank", "Email can't be blank"]
>>> jared.valid()
false

// ...

你可能感兴趣的:(JavaScript,xml,Web,REST,prototype)