2012-05-19 70 views
2

该代码存储数组中的鼠标移动坐标,并且应该将其发布在未载入的页面上。但它不发布。如果我改变Ajax post onbeforeunload不起作用

名称:移动

名称: “布拉布拉”

它的工作原理。意味着问题出在“移动”变量上。我怎样才能使它工作?

$(document).ready(function(){ 


var moves = []; 

$("html").mousemove(function(e){ 
moves.push(e.pageX + "x" + e.pageY) 
}); 


window.onbeforeunload = function() { 

$.ajax({ 

     type: "POST", 
     url: "mailyaz.php", 
     data: { 
     name: moves; 
     } 
     }); 

}); 

}); 
+8

你做异步的东西,同时重新加载/关闭该页面的服务器端称为server.php页面,这将是越野车。设置'async:false'来等待函数完成,这是我知道确保它通过服务器的唯一方式,否则在某些浏览器中会出现问题,并且它不会一直通过。 – adeneo

+0

不确定,但它只用一个小字符串而不是阵列工作的原因,只需几秒钟的鼠标移动就可以实现,这可能与事物的大小有关,请在[FIDDLE](http ://jsfiddle.net/gAsKb/) – adeneo

+0

我已经注意到,问题可能出在“动作”上。它不存储它。 – user198989

回答

2

你可以试试这个。 这是我几个月前开发的一个小例子。 在这种情况下,坐标存储在文本文件中,但是您可以用INSERT将其替换到数据库中。

在客户端把这个:

var moves = ""; //Now an String to store the Coords 

    $(document).ready(function(){ 
     //When you moves the mouse inside the Page then 
     //concat the Coords into the String var and add a Line-Brak at the end 
     $("html").mousemove(function(e){ 
      moves += (e.pageX + " x " + e.pageY + "\n"); 

     }); 

     //Here the magic happen: bind a function to onbeforeunload event that POST 
     //the String to the server 
     $(window).bind('beforeunload', function() { 

      $.post("server.php",{name:moves}); 

     }); 

    }); 

现在,您需要在其中包含

//Capture the String 
    $cursorMoves = ($_POST['name']); 

    $myFile = "testFile.txt"; 
    $fh = fopen($myFile, 'w'); 
    fwrite($fh, $cursorMoves); 
    fclose($fh); 
+0

无法正常工作。:S – user198989

+1

@ user198989我在Chrome 18.0.1025.162和Firefox 12上测试过它,效果很棒!如果您给我一封电子邮件,我可以向您发送整个项目。 –

+0

哦,我注意到我正在使用if语句,如if($ _ POST [name]){ 我现在删除了它并且它的工作。 – user198989

1

onbeforeunload必须返回一个字符串。但是,ajax请求将被显示的对话框阻止。如果用户接受并离开该页面,则该请求可能会被中断。

https://developer.mozilla.org/en/DOM/window.onbeforeunload

http://jsfiddle.net/sVU7K/1

+0

工作版本也没有返回任何东西。 – Andreas

+0

我意外地将mootools设置为lib。在这个版本中修复。如果取消“对话框”,您将在控制台中看到返回的请求。 – Trevor

+0

onbefore卸载时没有问题。正如我所说,如果我将变量改为“blabla”,它就可以工作。 – user198989