用户离开页面时如何执行操作

时间:2015-11-13 18:06:40

标签: javascript jquery

规格:

  1. 当用户离开页面时显示提醒。
  2. 当用户确认“离开此页面”(发送ajax请求并等待收到响应)时执行操作。
  3. 收到ajax响应后,请离开页面。
  4. 我的代码是:

     window.onbeforeunload = function (e) {
         e = e || window.event;
         if (e) {
             e.returnValue = 'Sure?';
         }
         $.ajax({
             url: '/api/Electronic/leave',
             dataType: "json",
             contentType: "application/json",
             cache: false,
             type: 'POST',
             data: myData,
             success: function (data) {
                 //how to leave this page?
             },
             error: function () {
                 console.log("Error");
             }
         });
         return 'Sure?';
     };
    

2 个答案:

答案 0 :(得分:0)

- 当用户离开页面并等待结果时,您可以执行同步ajax调用

      window.onbeforeunload=function(e){        

        var result = false;
        $.ajax({
            url: 'https://api.github.com/users/mralexgray/repos',
            type: 'GET',
            async: false,
            success: function (data) {

                //do whatever you want here
                for (var i = 0; i < 10000;i++){
                    console.log(i);
                }                                 
                result = true;
            },
            error: function (e) {
                console.log("error");                  
            }
        });

        if (result) {
            window.onbeforeunload = window.thisPage.closeEditorWarning;
        } else {
            var confirmationMessage = 'Somthing went wrong. If you leave your changes will be lost.';

            (e || window.event).returnValue = confirmationMessage;              
             return confirmationMessage; 
        }


    }

答案 1 :(得分:0)

  

当用户确认“离开此页面”(发送ajax请求并等待收到响应)时执行操作。

那是不可能的。当用户确认“离开此页面”时,您的脚本将被终止。