【发布时间】:2018-07-10 12:37:07
【问题描述】:
我的哈巴狗模板中有一个表单,可以使用我的 Phoenix 控制器的提交功能正常提交。我不想重新加载或重定向页面,所以我想我应该使用 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))
}
)
})
})
我错过了什么吗?
【问题讨论】:
-
请发布错误信息。
-
@mudasobwa
[debug] ** (Phoenix.Router.NoRouteError) no route found for POST /adaptives/6/invoices/3 (Enterprise.Router) -
让我猜猜:您的管道仅接受 html
plug :accepts, ["html"],而您没有处理json的管道,对吧? -
@mudasobwa 好的,我在管道中添加了它,但我仍然遇到同样的错误。如果我完全摆脱了 javascript 部分,我不会收到任何错误,并且控制器按预期工作,所以它不可能是导致问题的服务器端。但是,我仍然需要阻止页面刷新。
-
当然是服务器部分。当前端发送 JSON 并返回 JSON 响应时,您应该显式处理此路由。
标签: ajax elixir phoenix-framework