2012-05-19 111 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