简体   繁体   English

在表单提交之前发送Ajax请求

[英]Sending an Ajax request before form submit

Is it possible to send an ajax request in onsubmit() of a form? 是否可以在表单的onsubmit()中发送ajax请求? 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. 只需暂停表单提交,直到AJAX请求完成。

Make your form onsubmit attribute call the AJAX function and return false (which cancels the form submission). 使表单onsubmit属性调用AJAX函数并返回false(取消表单提交)。 When your AJAX call completes, submit the form programmatically. 当您的AJAX调用完成后,以编程方式提交表单。

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>

There is another way to solve this issue, that is you can make the ajax call as synchronous. 还有另一种方法可以解决此问题,即您可以将ajax调用设置为同步。

Example: 例:

xmlhttp.open("GET", imageUrlClickStream, false);

By this we can make sure that the form submission will wait until the ajax call get the response. 通过这个我们可以确保表单提交将等到ajax调用得到响应。

Replace onsubmit with onclick it work well for me because onsubmit going in loop. 用onclick替换onsubmit它对我来说效果很好,因为onsubmit进入循环。

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

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

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

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