gpt4 book ai didi

javascript - 当选择的元素发生变化时,Rails 更新表单的内容

转载 作者:行者123 更新时间:2023-11-30 13:34:42 24 4
gpt4 key购买 nike

我有一个带有一个选择框和三个文本输入框的表单。当选择框中的选项发生变化时,我想用与所选选项对应的值更新三个文本输入框。这些值是存储在服务器上的模型对象。

我正在使用 Rails 3 并试图让事情不引人注目,但我找不到一种干净的方法来做到这一点。我想出了几个可怕的、困惑的解决方案,但还没有一个干净的解决方案。将这一切联系在一起的好方法是什么?特别是,我在选择元素从服务器请求模型对象时遇到了问题。

这是生成表单的 View :

= form.select :region_id, region_options_for_select(@business_location.region), :prompt => '-- Region --'
= form.text_field :city
= form.text_field :state, :label => 'Province/State'
= form.text_field :country

因此,每当“区域”发生变化时,我都希望填充城市/州/国家/地区字段。请注意,区域也是表单本身的一部分。

最佳答案

在 jQuery 中,像这样的东西可以工作:

$("select").live("change", function(e) {
e.preventDefault();
$.ajax({
url: "/location/" + $(this).val(), //I think, it could be something else
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
//you're returning a JSON object, so just iterate through it and bind it to
//the value attributes of each field
},
error: function(xhr,exception,status) {
//catch any errors here
}
});
});

在 Rails 方面,在 LocationsController#show 中:

@location = Location.find(params[:id])
respond_to do |format|
format.json { render :json => @location.to_json, :status => 200 }
end

这就是它的大致工作方式。将您拥有的任何 Controller /模型名称替换为我编写的名称。

关于javascript - 当选择的元素发生变化时,Rails 更新表单的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331241/

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