如何使用Ajax从数据库中获取数据

时间:2018-10-12 12:31:58

标签: ruby-on-rails ruby ajax ruby-on-rails-5

成功函数不返回数据。

控制器代码如下

controller / manageprojects.rb

class Manageprojects

    respond_to :html, :json 

    def fetch_currency_symbol 
        @location = Location.find_by_country(params[:country]) 
        @currency_symbol = @location.currency 
        respond_to do |format|
            format.json { render json: @currency_symbol } 
            format.html 
        end
    end 

end    

view / manageprojects / new.html.erb

JavaScript函数如下所示,并且使用国家/地区参数发送了ajax请求

<script type="text/javascript">
  $("#manageproject_location").on('change', function() {

      var country = $('select#manageproject_location :selected').val();
     // alert(country);
        $.ajax({
        url: '/fetch_currency_symbol',
          data: { country : country },
          dataType: 'json',
          type: 'POST',
          success: function(result)
          {
            console.log(result);
            $('#manageproject_symbol').val(result);
          }
        });
  });
</script>

routs.rb
post '/fetch_currency_symbol', to: "manageprojects#fetch_currency_symbol", as: "fetch_currency_symbol"

1 个答案:

答案 0 :(得分:2)

我会考虑是否真的需要对ajax请求进行处理。您不能仅将符号作为数据属性附加到<option>元素上?

module LocationsHelper
  def location_options(locations)
    options_for_select(
      locations.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency}] }
    )
  end
end

此帮助器方法返回适用于rails select辅助器的数组数组,并假定位置具有名称属性,并且可以通过调用location.currency获得货币符号。使其适应您的实际设置。

然后您可以使用以下方法创建选择标签:

<%= f.select(:location_id, location_options(Location.all)) %>

这将使您可以简单地通过以下方式读取值:

// Use delegated handles to ensure compatibility with turbolinks
$(document).on('change', '#location_id', function() {
  var $elem = $(this).find('option:selected');
  $('#manageproject_symbol').val($elem.data("currency_code"));
});
<!-- this is just HTML to support the snippet -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/locations/manage" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="_method" value="patch" /><input type="hidden" name="authenticity_token" value="341Fo3drT5jyTlsTWcsosmclgBaXUqtxI8baubkdZOIlBGDUez/yc1wgW+XqEVcrHCS4U9hDKGAwcIpjtOb/Fw==" />
  <label>Location:
    <select name="location_id" id="location_id">
      <option data-currency_code="$" value="1">USA</option>
      <option data-currency_code="&pound;" value="2">Great Britain</option>
      <option data-currency_code="&#8377;" value="3">India</option>
    </select>
  </label>
  <label>Currency symbol: <input type="text" id="manageproject_symbol"/></label>
</form>