在表单提交之前发送一个Ajax请求 [英] Sending an Ajax request before form submit

查看:460
本文介绍了在表单提交之前发送一个Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在表单的onsubmit()中发送ajax请求?我一直在尝试,结果很差,主要是因为如果浏览器发送我的请求比发送原始表单需要更长时间,那么一旦加载页面的位置发生变化,我的请求就会被丢弃,所以有时候从来没有碰到服务器。



基本上,我想要做的是添加一个收集登录事件的审计日志收集器,我想以最小的入侵将其与现有应用程序挂钩。 b $ b

解决方案

这很容易实现。



使表单 onsubmit 属性调用AJAX函数,返回false(取消表单提交)。当您的AJAX调用完成时,以编程方式提交表单。



例如:

 < form name =myformonsubmit =javascript:startAjax(); return false;> 
...
< script type =text / javascript>
函数startAjax(){} //完成时调用ajaxComplete()
$ b函数ajaxComplete()
{
document.myform.submit();
}
< / script>


Is it possible to send an ajax request in onsubmit() of a form? I have been trying it and the results are flaky, mainly because probably if the browser happens to take longer sending my request than it takes sending the original form, my request is discarded as soon as the location of the loaded page change, so sometimes it never even hits the server.

Basically, what I want to do is add an audit log collector that collects login events, I want to hook that to existing apps with minimal invasion.

解决方案

This is easily achievable. Just hold off the form submission until the AJAX request completes.

Make your form onsubmit attribute call the AJAX function and return false (which cancels the form submission). When your AJAX call completes, submit the form programmatically.

For instance:

<form name="myform" onsubmit="javascript: startAjax(); return false;">
...
<script type="text/javascript">
function startAjax() {} // Calls ajaxComplete() when finished

function ajaxComplete()
{
  document.myform.submit();
}
</script>

这篇关于在表单提交之前发送一个Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆