1

我有一个带有选择框和三个文本输入框的表单。When the option in the select box changes, I want to update the three text input boxes with values corresponding to the selected option. 这些值是存储在服务器上的模型对象。

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

这是生成表单的视图:

= 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

因此,我希望在“地区”更改时填充城市/州/国家/地区字段。请注意,区域也是表单本身的一部分。

4

1 回答 1

3

在 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

这大概就是它的工作方式。用您拥有的任何控制器/型号名称替换我编造的名称。

于 2011-03-16T20:27:33.987 回答