我正在尝试创建一个动态表格,该表格使用AJAX从Rails端获取出租单位的计算价格。我正在获取每个出租单位的价格信息,格式为JSON(/companies/:id/locations/:id/units/:id/price.json)。
我的问题是在为每个单元设置text
的函数中。看来,它仅获取第一个单元的JSON,之后所有以下价格都设置为第一个单元
Request URL: /storage_companies/2/storage_locations/4/storage_units/10/price
{id: 10, monthly_cost: 7.25, total_price: 87}
在UnitController
中,我设置了一个price方法,以JSON输出价格信息:
def price
respond_to do |format|
format.json { render json: @storage_unit, methods: [:total_price], only: [:id, :monthly_cost, :total_price]}
end
end
和路线:
resources :companies do
resources :locations do
resources :units do
member do
get :price
end
end
end
end
如何重构它以遍历所有units
并设置text
?
$(function(){
var CompanyId = $('.storage_company').data('params-id');
var LocationId = $('.select_location').data('params-id');
var UnitId = $('.select_unit').data('params-id');
$.getJSON(`/companies/${CompanyId}/locations/${LocationId}/units/${UnitId}/price`, callbackFuncWithData);
function callbackFuncWithData(data){
$(".monthly_estimated_price").text("$" + data.monthly_cost.toFixed(2));
$(".total_estimated_price").text("$" + data.total_price.toFixed(2));
};
});
$.getJSON("/prices", function(data){
$.each(data, function (index, value) {
var price = value;
$(`.select_unit[data-params-id="${price.id}"]`).each(function(){
$(".monthly_estimated_price").text("$" + price.monthly_cost);
console.log(price)
});
});
});