大家好
我正在尝试解决这个问题,但还是做不到。
我有一个 Rails 3 应用程序,我正在处理发票和付款。在付款表单中,我有一个 collection_select,其中显示所有发票编号(从 postgres 数据库中提取),我想做的是当我选择发票时自动填充其他文本字段(提供商、地址等),而不需要以相同的形式重新加载页面。
我知道我应该使用ajax、js、jquery,但我是这些语言的初学者,所以我不知道如何或从哪里开始
希望你能帮助我...谢谢
最佳答案
您要做的是将 ajax 调用路由到 Controller , Controller 将使用包含信息的 json 进行响应。然后,您将使用 jquery 填充不同的字段。
在您的 route :
get "invoice/:id/get_json", :controller=>"invoice", :action=>"get_json"
在您的发票 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
...
});
});
您可能会遇到一些问题,如果您没有使用 google chrome,我强烈建议您下载并安装 fire bug。如果您使用的是,请确保您正在使用开发工具。我相信您可以通过右键单击并点击检查元素来打开它们。通过这个,你应该能够监控ajax请求,以及它是否成功等事情。
关于javascript - 根据Rails 3中另一个collection_select中的选定项目自动填充text_fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086142/