如何在页面重定向之前确保服务器请求已完成? [英] How do I ensure server request is complete before page redirect?

查看:67
本文介绍了如何在页面重定向之前确保服务器请求已完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了澄清一下,我的主要问题归结为:如果您向某台服务器(在本例中为Google的)发出AJAX请求,但随后客户端在服务器之前离开了页面完成请求后,服务器是否也有可能(或可能)中止请求,或者服务器将尝试完成请求(尽管没有人再响应)?

Just to clarify, my main question boils down to this: if you issue an AJAX request to some server (in this case Google's), but then the client leaves the page before the server completes the request, is it possible (or likely) that the server would abort the request as well, or would the server try to complete the request (in spite of having no one to respond to any more)?

如果需要,可以随时阅读其余所有内容.

Feel free to read the rest for all the specifics, if you want.

我在要立即重定向的页面上使用Google Analytics(分析).由于Google javascript文件 ga.js 是异步加载的,因此我需要确保跟踪由javascript动态添加的所有脚本标签,并且页面重定向仅在这些脚本完成之后发生.我已经处理了那部分.

I am using Google Analytics on a page that is meant to immediately redirect. Since the Google javascript file ga.js is loaded asynchronously, I need to make sure that all the script tags that are added dynamically by the javascript are tracked and that the page redirect only happens after those scripts complete. I already handled that part.

文件 ga.js 似乎是对具有参数的 __ utm.gif 文件的请求,该文件将执行实际的跟踪.该请求显然不是从我可以控制的文件发出的,所以这是我的问题:

The file ga.js seems to make a request to a __utm.gif file with parameters, which is what performs the actual tracking. That request obviously isn't being made from a file I can control, so here are my questions:

首先,请求是异步的吗(我怀疑是这样)?其次,如何确保在重定向页面之前该请求有时间完成(我宁愿不要在经过足够的时间"之后简单地重定向)?如果在请求完成之前重定向了原始页面,请求是否仍会完成(毕竟,我不需要从Google返回任何数据)?

First of all, is the request asynchronous (I suspect it is)? Secondly, how can I make sure that that request has time to complete before I redirect the page (I'd prefer not to simply redirect after "enough time" has passed)? Would the request still complete if the originating page redirected before the request was finished (after all, I don't need any data back from Google)?

编辑:这是我的代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Redirecting...</title>

     <script type="text/javascript">
        /* <![CDATA[ */

        // Holds a value for each script. When all the values contained in this array are true, all loading has completed.
        var scripts = [];

        function scriptDetectLoaded(script)
        {
            scripts.push({ loaded: false, element: script });
            var index = scripts.length - 1;

            // Will set this script as loaded
            var callback = function ()
            {
                //console.log("Script with index " + index + " finished loading");
                scripts[index].loaded = true;
            };

            // For most browsers
            script.onload = callback;
            // For IE
            script.onreadystatechange = function ()
            {
                if (this.readyState == "complete")
                    callback();
            };

            return index;
        }

        /* ]]> */
     </script>

     <!-- Google analytics code -->
     <script type="text/javascript">
        /* <![CDATA[ */
        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-MY_ID-1']);
        _gaq.push(['_trackPageview']);

        (function ()
        {
            //debugger;
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            scriptDetectLoaded(ga); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();
        /* ]]> */
    </script>
</head>
<body>
    <noscript>
        <p>Please enable JavaScript and refresh this page. Our site won't work correctly without it.</p>
        <p><a href="http://www.google.com/search?q=how+to+enable+javascript" target="_blank">How do I enable JavaScript?</a></p>
    </noscript>

<!-- Google Code for New Account Conversion Page -->
<script type="text/javascript">
    /* <![CDATA[ */
    //debugger;
    var google_conversion_id = SOME_ID;
    var google_conversion_language = "en";
    var google_conversion_format = "2";
    var google_conversion_color = "ffffff";
    var google_conversion_label = "SOME_LABEL";
    var google_conversion_value = 0;

    (function () {
        var gad = document.createElement('script'); gad.type = 'text/javascript'; gad.async = true;
        gad.src = document.location.protocol + "//www.googleadservices.com/pagead/conversion.js";
        scriptDetectLoaded(gad); var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gad, s);
    })();
    /* ]]> */
</script>
<noscript>
    <div style="display:inline;">
        <img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1056222251/?label=keCSCNO9qAIQq9jS9wM&amp;guid=ON&amp;script=0"/>
    </div>
</noscript>

    <!-- Redirect Page -->
    <script type="text/javascript">
        /* <![CDATA[ */
        //debugger;
        var url = '/console';
        var interval = 100 /*milliseconds*/;
        var timeout = 5000 /*milliseconds*/;
        var count = 0;

        // Set a repeating function that checks to ensure all the scripts have loaded.
        // Once all the scripts have loaded, redirect the page.
        var id = setInterval(function ()
        {
            count += interval;

            // Check for timeout
            if (count > timeout)
            {
                //console.log("Timed out.");
                redirect();
            }

            // Check to make sure all scripts have loaded
            for (var i = 0, len = scripts.length; i < len; i++)
            {
                if (!scripts[i].loaded)
                    return;
            }

            // If we make it here, redirect
            redirect();
        }, interval);

        function redirect()
        {
            location.replace(url);

            // Run this in case the page doesn't redirect properly.
            clearInterval(id);

            var a = document.createElement("a");
            a.href = url;
            a.innerHTML = "Please click here to proceed";

            var p = document.getElementById("message");
            p.innerHTML = "";
            p.appendChild(a);
        }
        /* ]]> */
    </script>

    <p id="message">Please wait as we redirect the page.</p>
</body>
</html>

推荐答案

如果在请求完成之前重定向,它将在客户端被取消.意思是,服务器可能已经收到帖子并采取了相应措施,但您不会获得结果.如果这些项是动态添加的,则不能使用任何onload类型的函数.我想您添加的google文件将具有某种回调类型,您可以使用该回调类型来重定向您.

If you redirect before the request completes, it will be cancelled on the client side. meaning, the server may have gotten the post and acted on it, but you will not get the results. if these items are added dynamically you cannot use any onload type of functions. i would imagine the google files your adding will have some type of callback you can use that will redirect you.

edit:如果要以某种方式加载脚本,则可以确切地知道何时完成加载,因此可以重定向到另一个页面,我将使用jquery的$ .getScript函数.文件加载后,它允许进行回调,然后您可以立即重定向 api.jquery.com/jQuery.getScript

edit: if you want to load the script in a way that you will know exactly when it is done loading so you can redirect to another page i would use jquery's $.getScript function. it allows for a callback once the file has loaded then you can redirect instantly api.jquery.com/jQuery.getScript

这篇关于如何在页面重定向之前确保服务器请求已完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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