Posting data to server async just before page redi

2019-09-19 15:29发布

It seems like a common problem, but I couldn't find related threads - please direct me if I missed something here.

we are using some sort of click tracker to our website. this tracker is getting calls when the user click on a link, we want to populate certain data to a different server, and let the user continue to the clicked url.

As I do not want to wait for the server response here- I am not waiting for response to this ajax call. but what happens is the I lose this call and it never gets to the server. What is the correct way to perfrom this action?

I am using top.window.location.href = url; as I sometimes get opened in an Iframe.

function onClick(url, clickedFrom) {
        var testClick = ServerHost + "click";
        var dataObject = buildCommonData();

        $.ajax({
            dataType: 'post',
            contentType: "text/json; charset=utf-8",
            data: dataObject,
            url: testClick,
            async: true,
            success: function (response) {
                top.window.location.href = url;

            },

        });
        top.window.location.href = url;

        return false;
    }

1条回答
做个烂人
2楼-- · 2019-09-19 16:09

Remove the second top.window.location.href = url; ... that is clobbering your $.ajax() call... and return false is never reached.


Consider using setTimeout and success: on the $.ajax() call!

You can double-up your approach here, and keep the second top.window.location.href call, but put it in a setTimeout block, in case there is an $.ajax() delay.

This way, the $.ajax() call should happen first, but if not, at least the user is not delayed if/when there is a server glitch that hangs up the $.ajax() call.

查看更多
登录 后发表回答