AJAX离开前页立即调用 [英] AJAX calls immediately before leaving page

查看:139
本文介绍了AJAX离开前页立即调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行当用户点击一个链接到另一个网页一个简单的AJAX GET请求。将Ajax调用完成还是会停止,因为用户离开发起AJAX请求的页面?我真的不关心从GET请求的响应。

I want to perform a simple AJAX get request when a user clicks a link to another page. Will the AJAX call complete or will it stop because the user is leaving the page that initiated the AJAX request? I don't really care about the response from the get request.

任何想法或意见?

推荐答案

如果你只是想将数据发送到服务器,并且不关心resonse,你可能会想尝试的请求。这主要是,火,忘记它的工作原理是这样的事情:

If you just want to send data to your server and don't care about the resonse, you might want to try a beacon request. That basically is, a fire and forget thing which works like this:

function sendInfo(something) {
     var beacon = new Image();
         beacon.src = '/somepath/script.pl?info=' + something;
}

$('a[href^=http]').bind('click', function(e) {
    sendInfo(escape(e.href));
});

那么,这种技术并不能阻止所以它可能是一个竞争条件的浏览器是否会触发请求(我没有这样的目的测试)。可以肯定的是,请求将触发,调用这样一个Ajax调用:

Well, this technique does not block so it might be a race condition whether or not the browser will fire the request (I didn't test it on this purpose). To be sure that the request will fire, invoke an ajax call like this:

$('a[href^=http]').bind('click', function(e) {
    $.get('/somepath/script.pl', {info: escape(e.href)}, function(data) {
        location.href = e.href;
    });

    return false;
});

这篇关于AJAX离开前页立即调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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