【问题标题】:Get Params from ajax response Rails从 ajax 响应 Rails 获取参数
【发布时间】:2012-01-14 03:16:59
【问题描述】:

我像这样在“贡献”控制器中创建了一个新动作

def newitem
    @Item = Item.new(:description => params[:description], :type_id => params[:type])
    if @Item.save
     #Magic supposed to happen here
   end
  end

因此,在此操作中,我创建了一个新的“项目”,我想要实现的是从 AJAX 响应中创建的项目中获取 id,因此我可以在创建“项目”的同一视图中使用它。 ..

第一个问题,如何从控制器发回创建项目的参数? 第二,我知道如何处理 Ajax 请求,但是如何处理对第一个请求的 Ajax 响应......

也许我在考虑解决方案,但无法弄清楚如何去做。 提前致谢。

【问题讨论】:

    标签: ruby-on-rails ajax ruby-on-rails-3 jquery


    【解决方案1】:

    有几种方法可以解决这个问题。下面解释的方法适用于 Rails 3.1

    直接在您的方法中调用渲染(这种方法对于仅 JSON API 的方法很有帮助。因为 html 渲染将不存在):

    def newItem
        @Item = Item.create(:description => params[:description], :type_id => params[:type])
        render json: @Item
    end
    

    使用 respond_do 块:

    def newItem
      @Item = Item.create(:description => params[:description], :type_id => params[:type])
    
        respond_to do |format|
        if @Item.save
          format.html { redirect_to @Item, notice: 'Item was successfully created.' }
          format.json { render json: @Item, status: :created, location: @Item 
        else
          format.html { render action: "new" }
          format.json { render json: @Item.errors, status: :unprocessable_entity }
        end
      end
    end
    

    教你的控制器你想要的响应格式:

    class ContributionsController < ApplicationController
      # Set response format json
      respond_to :json
    
      ...
    
      def newItem
        @Item = Item.create(:description => params[:description], :type_id => params[:type])
        respond_with @Item  #=> /views/contributions/new_item.json.erb
      end
    

    可能的“陷阱”...

    如果您在创建项目时出现验证失败,您将无法取回 id,也不会报告失败(除了 http 响应代码)

    将以下内容添加到您的模型中。它将在 json 响应中的错误哈希中包含验证失败

     class Item < ActiveRecord::Base
    
       ...
    
       # includes any validation errors in serializable responses 
       def serializable_hash( options = {} ) 
         options = { :methods => [:errors] }.merge( options ||= {} )
         super options
       end
    

    给猫剥皮的方法总是不止一种。我希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 1970-01-01
      • 2015-06-01
      • 2014-10-29
      • 2014-07-19
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多