gpt4 book ai didi

javascript - rails : Changing form method to PATCH in javascript sends a GET request on form submit

转载 作者:行者123 更新时间:2023-12-01 01:24:30 24 4
gpt4 key购买 nike

我有一个默认情况下为POST的表单。在更改下拉菜单时,我想将表单方法更改为 PATCH 并将其操作更改为其他内容并提交表单。

erb:

<%= form_for @booking, :url => admin_events_bookings_path, :html => { :class => 'smart-form', :id => 'mainForm', :data => { :change_event_path => change_event_admin_events_bookings_path } } do |f| %>
...
<% end %>

HTML(呈现):

<form class="smart-form" id="mainForm" data-change-event-path="/admin/events/bookings/change_event" action="/admin/events/bookings" accept-charset="UTF-8" method="post" novalidate="novalidate"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="oC9bO0GVnMuc4UFnJLKDbTvaWEPLCKycmrsTJGWcHyYZ2QrYsVzbvP1pmMmqF/LIT3BepGCTWhZ0YZyPGsJUPg==">
...
</form>

JS:

$('#booking_event_id').on('change', function(ev) {
$('#mainForm').attr('action', $('#mainForm').data().changeEventPath) //this works, verified in browser
$('#mainForm').attr('method', 'patch') //this works, verified in browser
$('#mainForm')[0].submit()
})

但是到达服务器的请求是 GET 请求。从日志中:

Started GET "/admin/events/bookings/change_event?utf8=%E2%9C%93&authenticity_token=oizowirdfSiR%2BiUGIsZWe8PHSypUAItFK8Y39gwNtK4b2rkh2hQ6X%2FBy%2FKisYyfet21Nzf%2Bbfc%2FFHLhdc1P%2Ftg%3D%3D&ticket_type=priced&booking%5Bevent_id%5D=2"

为什么表单作为 GET 请求提交?我怎样才能做到这一点?

最佳答案

根据Rails docs :

If the verb is not GET or POST, which are natively supported by HTML forms, the form will be set to POST and a hidden input called _method will carry the intended verb for the server to interpret.

因此,要更改动词,您只需在名为 _method 的表单中添加一个隐藏字段,其值为 patchput:

<input type="hidden" name="_method" value="patch">

关于javascript - rails : Changing form method to PATCH in javascript sends a GET request on form submit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53930835/

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