gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:20:37 25 4
gpt4 key购买 nike


大家好

我正在尝试解决这个问题,但我还是做不到。

我有一个 Rails 3 应用程序,我正在处理发票和付款。在付款表格中,我有一个 collection_select,我在其中显示所有发票编号(从 postgres 数据库中提取),而我想要做的是当我选择发票时自动填充其他文本字段(提供商、地址等)而不以相同的形式重新加载页面。

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

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

最佳答案

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

在你的 route :

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
...
});
});

您可能会遇到一些问题,如果您没有使用谷歌浏览器,我强烈建议您下载并安装 fire bug。如果您使用的是,请确保您使用的是开发工具。我相信您可以通过右键单击并点击检查元素来打开它们。通过这个,您应该能够监控 ajax 请求,以及它是否成功等等。

关于javascript - 根据 Rails 3 中另一个 collection_select 中的选定项目自动填充 text_fields,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8086142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com