在 WordPress 自定义模板表单中使用 jQuery .post 函数
我目前正在 WordPress 网站上创建一个自定义联系表单,我试图通过 ajax 使用 jQuery 提交该表单,但是当我执行 $.post 函数时,firebug 在控制台中报告 404 错误,即使我可以键入URL 到我的地址栏并正确显示页面。我不会跨域发帖。
这是我的代码示例,删除了不相关的代码:
<form action="" method="post" onsubmit="return submitContactForm()" class="contactform">
<!-- inputs etc here -->
</form>
<script type="text/javascript">
function submitContactForm() {
// Omitted error checking here, return false on error
$.post('/contact'/, $('.contactform').serialize(), function(data) {
alert(data);
return false;
});
return true;
}
</script>
帖子永远不会成功,表单每次都会以“正常”方式提交。
我在 $.post 的 url 部分尝试了多种组合,包括 /contact/ 、 /contact 、 contact 、 /contact/ ,甚至网站的完整 url 都没有成功。以前有人遇到过这个问题吗?或者我做错了什么?我唯一的猜测是与我的 /%postname%/ 永久链接结构有关,除此之外我一无所知!
任何想法/想法表示赞赏
谢谢,安迪
I'm currently whipping up a custom contact form on a wordpress site which I'm trying to submit via ajax with jQuery, however when I perform the $.post function, firebug is reporting a 404 error in the console even though I can type the URL in to my address bar and display the page correctly. I am not posting cross-domain.
Here is an example of my code, with irrelevant code removed:
<form action="" method="post" onsubmit="return submitContactForm()" class="contactform">
<!-- inputs etc here -->
</form>
<script type="text/javascript">
function submitContactForm() {
// Omitted error checking here, return false on error
$.post('/contact'/, $('.contactform').serialize(), function(data) {
alert(data);
return false;
});
return true;
}
</script>
The post is never successful and the form submits the "normal" way every time.
I've tried many combinations in the url part of $.post including /contact/ , /contact , contact , /contact/, even the full url of the site with no luck. Has anybody had this issue before? Or am I doing something blatantly wrong? My only guess is something to do with my /%postname%/ permalink structure, other than that I'm clueless!
Any ideas/thoughts appreciated
Thanks, Andy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是 jQuery 文档中的内容:
试试这个:
This is in jQuery documentation:
Try this:
我终于明白是怎么回事了。基本上 ajax 发布是异步执行的,因此在收到响应之前,脚本继续处理
将 async: false 添加到 $.ajax 调用解决了问题
感谢您的帮助
I finally figured out what's going on. Basically the ajax post was being performed asynchrounously, so before the response had been receieved the script continued processing
Adding async: false to a $.ajax call solved the problem
Thanks for the help