简体   繁体   English

如何处理使用 JQuery 提交的表单

[英]How to handle form submitted with JQuery

I have a multistep form.我有一个多步表单。 I'm validating each step with Javascript before submitting it to PHP.在将其提交给 PHP 之前,我正在使用 Javascript 验证每个步骤。

If the form's last step passes validation tests.如果表单的最后一步通过验证测试。 I'm submitting the form.我正在提交表格。 like so像这样

$(UISelectors.addListForm)[0].submit();

I want to handle form submission with Javascript and submit it to PHP with Ajax.我想用Javascript处理表单提交并用Ajax提交给PHP。 but instead, the page refreshes.相反,页面会刷新。

const addListingSubmit = (e) => {
  e.preventDefault();

 // ...
};

$(UISelectors.addListForm).submit(addListingSubmit);

Any suggestions?有什么建议?

Here is my code: https://jsfiddle.net/cd1mkuge/1/这是我的代码: https : //jsfiddle.net/cd1mkuge/1/

An HTML form natively calls a defined url (for which the code is missing in your question) when it is submitted, and thus will leave the current page. HTML 表单在提交时本机调用已定义的 url(您的问题中缺少该代码),因此将离开当前页面。 To avoid this behaviour use a click handler (on the form's submit button) instead, and do your ajax call in there with the form's values:为避免这种行为,请改用单击处理程序(在表单的提交按钮上),并在其中使用表单的值执行 ajax 调用:

const onClick = e => {
    // get values from the form
    const foo = $("#foo-field").val();
    // etc.

    // do AJAX call
    $.post(...)
};

$('#my-button').click(onClick);

This way, the form's submit event is never triggered.这样,表单的提交事件永远不会被触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM