将字符串从控制器返回到ajax调用的最佳方法

时间:2014-11-11 10:10:25

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

我想创建一个返回单个字符串值的操作:

def delay_calulation()
  dr = Dr.find(params[:id])
  delay = dr.calc()

  respond_to do |format|
    format.json { render json: {"value" => delay}}
  end
end

但我在ajax电话中“失败”:

$("#btn_delay").on("click", function () {
    $.ajax({
      type: "GET",
      dataType: "script",
      url: "/drs/delay_calulation/1"
    })
    .done(function(response){
        console.log(response);
    })
    .fail(function(response){
        console.log(response);
    });

  });

如何获得单个字符串或类似字符串。

1 个答案:

答案 0 :(得分:1)

您需要在通过Ajax调用时将id传递给控制器​​操作。您可以使用控制器中提到的密钥名称来检索字符串。

$.ajax({
            url: '/drs/delay_calulation',
            data: {id: (you need to pass the id)},
            type: "get",
            dataType: "json",
            success: function(data){
                       var a = data["delay"]
            },
            failure: function(data){
                var a = data["delay"]
            }
        });
相关问题