2017-06-14 76 views
1

我對於ajax和jquery很新穎!Ajax請求不適用於移動設備

在下面,我的代碼在臺式電腦上的魅力。

我可以爲客戶收集花費的時間,但是在移動設備中,ajax請求不起作用。

這裏是我的代碼:

<script type="text/javascript"> 
var startTime = new Date();  //Start the clock! 
window.onbeforeunload = function()  //When the user leaves the page(closes the window/tab, clicks a link)... 
{ 
    var endTime = new Date();  //Get the current time. 
    var timeSpent = (endTime - startTime);  //Find out how long it's been. 
    var xmlhttp;  //Make a variable for a new ajax request. 
    if (window.XMLHttpRequest)  //If it's a decent browser... 
    { 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest();  //Open a new ajax request. 
    } 
    else  //If it's a bad browser... 
    { 
     // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  //Open a different type of ajax call. 
    } 
    var url = "http://www.example.com/time.php?time="+timeSpent;  //Send the time on the page to a php script of your choosing. 
    xmlhttp.open("GET",url,false);  //The false at the end tells ajax to use a synchronous call which wont be severed by the user leaving. 
    xmlhttp.send(null);  //Send the request and don't wait for a response. 
} 
</script> 

它爲我的手機(iphone)不工作!

任何人都可以幫助我嗎?

謝謝!

+0

你能確認你正在測試什麼移動設備嗎? – mjw

+0

只有Iphone 6,蘋果設備,我測試過 – Bagova

+0

你在問題(iPhone)中回答了它。 – mjw

回答

0

我認爲這個問題是由移動設備不支持window.onbeforeunload的事實造成的。有類似的效果,嘗試document.unloaddocument.pagehide

0

試試這個:

<script type="text/javascript"> 
var startTime = new Date();  //Start the clock! 
var isOnIOS = navigator.userAgent.match(/iPad/i)|| navigator.userAgent.match(/iPhone/i); 
var eventName = isOnIOS ? "pagehide" : "beforeunload"; 

window.addEventListener(eventName, function (event) { 
    var endTime = new Date();  //Get the current time. 
    var timeSpent = (endTime - startTime);  //Find out how long it's been. 
    var xmlhttp;  //Make a variable for a new ajax request. 
    if (window.XMLHttpRequest)  //If it's a decent browser... 
    { 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest();  //Open a new ajax request. 
    } 
    else  //If it's a bad browser... 
    { 
     // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  //Open a different type of ajax call. 
    } 
    var url = "http://www.example.com/time.php?time="+timeSpent;  //Send the time on the page to a php script of your choosing. 
    xmlhttp.open("GET",url,false);  //The false at the end tells ajax to use a synchronous call which wont be severed by the user leaving. 
    xmlhttp.send(null);  //Send the request and don't wait for a response. 
}); 
</script> 

此事件將兩種瀏覽器和iOS設備以及工作。

+0

@Bagova這個解決方案適合你嗎?讓我知道,以便它也能幫助別人。謝謝 –

相關問題