Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

javascript - Ajax post onbeforeunload doesn't work

This code stores mouse movement coordinates in array and it should post it onbeforeunload. But it doesn't post. If I change

name: moves
to
name: "blabla"

it works. Means that the problem is on the "moves" variable. How can I make it working ?

$(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;
      }
      });

});

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try this. It's a little example that I develop some months ago. In this case the coordinates are stored in a Text File, but you can replace this with an INSERT into a DataBase.

On the client Side put this:

    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 + "
");

        });

        //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});

        }); 

    });

Now you need a Page in the server side called server.php which contains

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...