根据Rails 3中另一个collection_select中的选定项自动填充text_fields

时间:2011-11-10 20:53:23

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


Hello people

我想弄清楚这一点,但我仍然无法做到。

我有一个rails 3应用程序,我正在处理发票和付款。在付款的形式我有一个collection_select我显示所有发票号码(从postgres数据库中提取),我正在尝试做的是当我选择一个发票自动填充其他text_fields(提供商,地址等)没有以相同的形式重新加载页面。

我知道我应该使用ajax,js,jquery,但我是这些语言的初学者,所以我不知道如何或从哪里开始

希望你能帮助我......谢谢

1 个答案:

答案 0 :(得分:3)

您要做的是将ajax调用路由到控制器,该控制器将使用包含该信息的json进行响应。然后,您将使用jquery填充不同的字段。

在您的路线中:

get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"

在invoice_controller中:

def get_json
  invoice = Invoice.find(params[:invoice_id])
  render :text => invoice.to_json
end

在您的发票模型中(如果默认的to_json方法不够):

def to_json
  json = "{"
  json += "id:'#{self.id}'"
  json += ",date_created:'#{self.date}'"
  ...      //add other data  you want to have here later
  json += "}"
end

在您的javascript文件中,

$("#invoice_selecter").change(function(){  //calls this function when the selected value changes
  $.get("/invoice/"+$(this).val()+"/get_json",function(data, status, xhr){  //does ajax call to the invoice route we set up above
    data = eval(data);  //turn the response text into a javascript object
    $("#field_1").val(data.date_created);  //sets the value of the fields to the data returned
    ...
  });
});

你可能会遇到一些问题,如果你不是谷歌浏览器,我强烈建议下载和安装防火虫..如果你是,请确保你使用的是开发工具。我相信你可以通过右击并点击检查元素打开它们。通过这个,您应该能够监视ajax请求,以及它是否成功以及事情。