0

我正在使用 PHP/jQuery 并有以下场景:

我有一个site1.php带有链接的站点 (),该链接指向另一个站点 ( site2.php),我还在此链接中添加了一个带有 jQ​​uery 的 ajax-onclick-event,它请求另一个站点 ( ajaxcall.php)。这个其他网站有“很多工作”要做,所以这不是一个简短的请求。

我的目标是:将请求设置为ajaxcall.php在后台(异步)并立即转到site2.php. (我不需要答案ajaxcall.php

我的第一个实现是这样的:

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
        $("#link").on("click",function(){
            $.get('./ajaxcall.php');
    </script>
</head>
<body>
    <a href="./file2.php" id="link">link</a>
</body>
</html>

显然这行不通。因为 ajax-request(它是异步的),一旦页面被改变就被中止。

据我所知,我在这里有两种可能性:

  1. 使请求同步并显示加载指示器 ( $.ajax({url: './ajaxcall.php',async:false});)
    --> 缺点:在完成file2.php之前不会打开ajaxcall.php

  2. 打开一个window.open('ajaxcall.php')file2.php窗(

  3. ???更好的方法???

我希望你明白我想要完成的事情并且你能帮助我:)

4

3 回答 3

1

试试这个代码...

$(document).ready(function() {
    $("#link").on("click",function(e){
        e.preventDefault();
        var href = this.href;
        $.get('./ajaxcall.php', function() {
            window.location.href = href;
        });
    });
});

它停止执行链接(使用e.preventDefault()),获取目标 url,然后在获取请求完成时将页面重定向到该位置。

于 2013-02-14T15:00:56.237 回答
0

那么你ajaxcall.php不能通过传递一个参数来开始里面的动作file2.php吗?就像:

file2.php?startBackgroundAction=true

文件2.php:

if($_GET['startBackgroundAction']) {
   include 'ajaxCall.php' // with ignore_user_abort(true)
}
于 2013-02-14T15:01:42.487 回答
0

最新的 chrome 浏览器不会完成 ajax 请求。由于浏览器页面从用户那里得到了新的 url 请求,所以浏览器会立即终止线程。

98% 的情况下,您可以看到 ajax 请求在网络选项卡中被取消。

所以解决方案是使用 sendBeacon API。这将异步执行 POST 请求。
Google 分析使用此代码执行事件跟踪(例如:点击)。
https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon

 navigator.sendBeacon("{{url}}", param);
于 2019-06-20T09:16:32.267 回答