";Aftersend”;Ajax调用的事件


"Aftersend" event for Ajax calls?

$.ajax调用一个执行许多操作的PHP页面。我希望我的用户可以在PHP脚本收到请求后关闭页面。

我如何知道脚本何时收到请求?

类似。。。

$.ajax({
    url: "/my-huge-script", 
    type: "POST",
    ...
    ...
    afterSend: function(){
        alert('The script has received the request. You can close the browser.');
    }
}

提前表示感谢,并为我糟糕的英语感到抱歉。

更新

我试过了:

JS:

$.ajax({
    url: "/huge-page",
    dataType: "json",
    type: "POST",
    data: { 
        ... LARGE DATA! (base64 file)
    },
    success: function() {
        alert('The script has received the request. You can close the browser.')
    }
})

HUGE-PAGE.php

<?php
header('Content-Type: application/json');
echo json_encode(array('Success' => "get it"));
... MANY operations ...
?>

但是"success"只在PHP脚本的末尾触发

发送到PHP页面的$_POST数据大小各不相同,因此我希望用户知道请求何时完成。。。而无需等待PHP脚本的结束。

好吧,您可以在huge.php页面上打印出一些json

在你的页面顶部,你可以做一些类似的事情

echo json_encode(array('succes' => "get it"));

你应该使用:

success: function(response){
    //...
}

ajax调用中的success函数中,检查是否收到此消息,然后在那里添加alert

尝试您的HUGE-PAGE.php文件:

<?php
    header('Content-Type: application/json');
    // operations should before output 
    // so =>
     ... MANY operations ...
    // output at end of the file and exit()
    // so => 
    echo json_encode(array('Success' => "get it"));
    exit();
?>

我认为Jquery ajax的always((回调函数会为您工作。请参阅下面的示例代码。

 var jqxhr = $.ajax( "example.php" )
  .done(function() {
   alert( "success" );
 })
 .always(function() {
   alert( "complete" );
  });

jqXHR.always(函数(data|jqXHR,textStatus,jqXHR|errorThrown({});完整回调选项的替代构造.always((方法替换了已弃用的.complete((方法。

作为对成功请求的响应,函数的参数是与.done((相同:data、textStatus和jqXHR对象。对于失败的请求参数与.fail((的参数相同:jqXHR对象、textStatus和errorThrown。请参阅deferred.always((了解实现细节。

只是提醒一下success回调方法已贬值,您需要使用.done((而不是success((回调函数。