gpt4 book ai didi

javascript - Rails AJAX 将变量从 Controller 传递到部分不起作用

转载 作者:行者123 更新时间:2023-12-03 10:21:26 25 4
gpt4 key购买 nike

我在将变量从 Controller 异步传递到部分 Controller 时遇到问题。我希望发生的是在用户从下拉菜单中选择一个选项后,在我的 View 上呈现一个表单。问题是我不断收到此错误:

undefined local variable or method `shipment_options' for #<#    <Class:0x007f92941be8f0>:0x007f929ca78ad8> 

即使我使用类似 locals: { var: @var } 或类似的东西。这是我认为的代码:

<body>
<p>
This is the body<br>

<%= select_tag :service, options_for_select(usps_services), { id: "service_select", remote: true } %><br>

<div id='shipment_option'>
<%= render 'shipment_option', remote: true, locals: { shipments: @shipment_options } %>

</div>
</body>
<script>
$('#service_select').on('change', function () {
var service = $('#service_select').val();
$.ajax({
type: "POST",
url: '/service_select',
format: 'js',
data: { service: service, order_id: <%= params[:order_id] %> },
success: function (data) {
console.log(data.rates);
return true;
},
error: function (data) {
return false;
}});

});
</script>

处理 AJAX 请求的路由

# AJAX
# get '/ajax/:service' => 'dashboards#get_shipment'
post '/service_select' => 'dashboards#get_shipment'

Controller 中的get_shipment方法

def get_shipment
order = Order.find(params[:order_id])
respond_to do |format|

from_address = EasyPost::Address.create(
:street1 => Rails.configuration.from_address[:street1],
:street2 => Rails.configuration.from_address[:street2],
:city => Rails.configuration.from_address[:city],
:state => Rails.configuration.from_address[:state],
:zip => Rails.configuration.from_address[:zip]
)

to_address = EasyPost::Address.create(
:name => order.name,
:street1 => order.street1,
:street2 => order.street2,
:city => order.city,
:state => order.state,
:zip => order.zip
)

parcel = EasyPost::Parcel.create(
:predefined_package => params[:service],
:weight => 10
)

@shipment_options = EasyPost::Shipment.create(
:to_address => to_address,
:from_address => from_address,
:parcel => parcel
)
# format.json { render json: ActiveSupport::JSON.encode(shipment_option) }
format.js { render json: @shipment_options, action: "new" }
end

结束

以及我尝试渲染的部分中的代码

<%= form_for(@shipment) do |f| %>
<% shipment_options.rates.each do |rate| %>
<%= f.label :shipment_service %>
<%= rate.service + " " + rate.rate.to_s %>
<%= f.check_box :shipment_service %>
<% end %>
<%= f.submit "Ship package" %>
<% end %>

如何消除这个错误?谢谢。

最佳答案

看起来您将@shipment_options作为发货传递给您的部分,但在您的部分中您正在调用尚未定义的shipment_options。

关于javascript - Rails AJAX 将变量从 Controller 传递到部分不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613708/

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