确保在更改页面后完成请求

时间:2013-02-13 12:26:50

标签: javascript ajax

问题是:我有使用JavaScript发送日志的自定义分析引擎。我想在用户提交表单后发送日志。使用AJAX发送日志。现在的问题是,表单提交不是AJAX,刷新页面是正常的请求。

我已经了解到即使客户端中止连接也可以强制执行脚本

Does php execution stop after a user leaves the page?

我想学习的是,如果在发送AJAX调用后几乎立即提交表单,如何确保服务器重新获取请求和标题?

2 个答案:

答案 0 :(得分:0)

var url = "...";
var my_form = document.getElementsByTagName("form")[0];
var request_received = false;

my_form.addEventListener("submit", function(e) {
    if (!request_received) {
        e.preventDefault(); // prevent the form from submitting

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState >= 2 && !request_received) {
                request_received = true;
                my_form.submit(); // submit the form only if the request has been received
            }
        };
        xhr.open("GET", url, true);
        xhr.send();

        return false;
    }
}, false);

答案 1 :(得分:-1)

让我们说这是带有提交按钮的表单:

<form id="myForm" action="/myAction.html" method="POST">

    <!-- form inputs -->
    <input type="submit" value="submit me!" />

</form>

使用JavaScript,您可以绑定到表单的提交事件,执行ajax调用,然后返回true以继续将表单提交到服务器:

<script type="text/javascript">

document.getElementById('myForm').addEventListener('submit', function(e){
    // do your ajax call here and when you finish, return true from
            // this function (in the ajax success callback)
    return true;
});

</script>