ruby-on-rails - 如何使用ajax从数据库中获取数据
问题描述
成功函数不返回数据。
控制器代码如下
控制器/管理项目.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
查看/管理项目/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"
解决方案
我会考虑是否真的需要用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 帮助的数组数组,并假设位置有一个 name 属性,并且您可以通过调用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="✓" /><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="£" value="2">Great Britain</option>
<option data-currency_code="₹" value="3">India</option>
</select>
</label>
<label>Currency symbol: <input type="text" id="manageproject_symbol"/></label>
</form>
推荐阅读
- bash - 如何从自托管 ubuntu docker 容器内部访问 junit 测试 - 在 Azure 发布管道中运行
- javascript - 使用 XMLHttpRequest 获取服务器中的文件存在
- angular - 无法在没有匿名身份验证的情况下从 Angular POST 到 .NET Core Web API
- java - 仅重置时间并将其转换为 java 中的 utc
- python - 用 Python3 合并两个视频
- python - 开始 Kaggle 问题:GCP 中的 Microsoft 恶意软件分类
- css - 为什么我的 CSS 在部署后似乎发生了变化?
- node.js - 在 GraphQL 中按 ID 排序
- java - Spring boot JWT auth by user id
- python - 访问数据框中的嵌套字典数据