jQuery.ajax() with window.onbeforeunload 不发送数据


jQuery.ajax() with window.onbeforeunload not sending data

我试图存储访问者在网站上花费的点击次数和时间的数据

我用这个 ajax 调用将数据发送到我的 php 文件。

window.onbeforeunload = function(){
  var endTime = new Date();  
  var timeSpent = (endTime - startTime);
  $.ajax({ 
    url: baseUrl + siteDir + pathToDataXml,
    type: "POST",
    datatype: "html",
    data: 'time='+timeSpent+'&clicks='+count,
    })
return "Thank You For Participating";
}    

当新记录输入数据库时,AJAX 调用正在命中 PHP 文件,但记录为空。

任何建议都会很棒

有时显而易见的问题是最难的,因为它们被忽视了

如果要通过 URL 参数发送数据,则应使用 $_GET 而不是 $_POST

试试这个

$( window ).unload(function() {
      var endTime = new Date();  
      var timeSpent = (endTime - startTime);
      $.ajax({ 
        url: baseUrl + siteDir + pathToDataXml,
        type: "POST",
        datatype: "html",
        data: 'time='+timeSpent+'&clicks='+count,
        })
    return "Thank You For Participating";
    });