【问题标题】:Get data back from controller method or helper in rails 3 to ajax从rails 3中的控制器方法或助手获取数据到ajax
【发布时间】:2011-01-21 02:42:07
【问题描述】:

我有一个从 _form.html.erb 调用的以下 javascript。

$.ajax({
type: "GET",
url: "/articles/" + $(this).attr('value'),
success: function(data){}
});

我想从这个请求中取回某种数据(可能是 json 对象或 Article 对象)。我不确定我是否需要打电话给帮手。当我调用控制器时,它返回给我的只是来自相应视图的 html 响应。

【问题讨论】:

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


    【解决方案1】:

    您可能应该使用控制器中的 respond_to 块根据格式生成不同的响应。

    def show
      @article = Article.find(params[:id])
      respond_to do |format|
        format.html
        format.json { render :json => @article }
      end
    end
    

    这样,模板将为所有带有 html 标头的标准请求呈现,但如果您发送带有 json 标头的 ajax 请求,它将呈现解析为 json 的文章。

    更新:

    使用以下 ajax 调用将 json 指定为预期响应:

    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/articles/" + $(this).attr('value'),
        success: function(data){}
    });
    

    【讨论】:

    • 我得到的响应是 html 响应。基本上我在 observe_field 中有一个函数,我在其中进行 GET 调用。因此,我需要将 json 对象返回到我拥有该字段的请求,以便我可以更新该页面中的字段。
    【解决方案2】:

    另一个带参数的例子:

    JS:

    $( "#booking_addr_edit" ).click(function(event) {
              var addressid = $('#appointment_order_currentaddress').val();
                $.ajax({
                  type: "GET",
                  dataType: "json",
                  data: {address_id: addressid},
                  url: '/booking/get_client_address',
                  success: function(data){
                    $('#appointment_order_address').val(data[0].street +' '+ data[0].city + ' ' + data[0].state);
                    $('#appointment_order_phone').val(data[0].phone);
                    $('#appointment_order_apartment').val('');
                    $('#booking_client_details').show();
                  }
                });  
                event.preventDefault();
            });
    

    控制器

      def get_client_address
        @address = Address.where(id: params[:address_id])
        respond_to do |format|
          format.js { render :json => @address }
        end
      end
    

    路线

     match "booking/get_client_address" => "booking#get_client_address"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-13
      • 2011-11-24
      • 2017-05-25
      • 1970-01-01
      • 2017-01-13
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多