我的哈巴狗模板中有一个可以正常使用的表单,并且可以使用Phoenix控制器的Submit函数正常提交。我不想重新加载或重定向页面,所以我认为我应该使用AJAX请求来提交表单。
这是表格:
=form_for @invoice_changeset, adaptive_invoice_path(@conn, :update, @adaptive, @invoice), [as: :invoice, method: :put, id: 'add-invoice-remarks-form'], fn f ->
.form-group
.label Remarks
= textarea f, :remarks, id: "remarks-area", role: "add-invoice-remarks", class: "textarea", placeholder: "Add Notes here (enter to submit)"
.form-group
= submit "Submit", class: "btn btn-primary btn-block"
这是我控制器中处理表单提交的函数。它可以正常工作,但是会刷新页面。
def update(%Plug.Conn{assigns: %{adaptive: adaptive}} = conn, %{
"id" => id,
"invoice" => invoice_params
}) do
{:ok, invoice} = Billing.find_invoice(%{"id" => id})
case Billing.update_invoice(invoice, invoice_remarks) do
{:ok, invoice} ->
conn
|> put_flash(:info, "Invoice update successful!")
|> redirect(to: adaptive_invoice_path(conn, :show, adaptive, invoice))
{:error, _changeset} ->
conn
|> put_flash(:error, "Something went wrong while adding remarks!")
|> redirect(to: adaptive_invoice_path(conn, :show, adaptive, invoice))
end
end
我试图截取该表单,并使用AJAX和onmount提交,但是即使我有正确的路线,也可以通过单击“提交”按钮收到Phoenix.Router.NoRouteError
。
import { post } from '../../api'
onmount('[role="add-invoice-remarks"]', function () {
const $form = $('#add-invoice-remarks-form')
$form.on('submit', e => {
e.preventDefault()
const action = $form.attr('action')
const invoiceParams = {
remarks: $form.find('#remarks-area').val()
}
post(
action,
{
invoice: invoiceParams
},
_ => {
show_flash(success_content())
},
response => {
show_flash(fail_content(response))
}
)
})
})
有什么我想念的吗?
答案 0 :(得分:1)
您正在将POST请求发送到需要PUT请求的路由。
除了发票参数外,您还需要一个_method="put"
参数。
类似的东西:
{
invoice: invoiceParams,
_method: "put"
}