2017-06-14 10 views
1

私はajaxとjqueryのために新しいです!モバイルデバイスでAjaxリクエストが機能しない

以下では、私のコードはデスクトップPCの魅力として働いています。

クライアントの使用時間を収集できますが、モバイルデバイスでは、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)用doesntの仕事!

誰でも私を助けてくれますか?

ありがとうございます!

+0

テストしているモバイルデバイスを確認できますか? – mjw

+0

Iphone 6のみ、appleのデバイスは、私がテストした – Bagova

+0

あなたは質問(iPhone)でそれを答えました。 – mjw

答えて

0

この問題は、モバイルデバイスがwindow.onbeforeunloadをサポートしていないという事実によって引き起こされたと思います。同様の効果を持つために、試すdocument.unloadまたはdocument.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このソリューションはあなたのために機能しますか?それが他の人にも役立つように私に教えてください。ありがとう –

関連する問題