2017-06-14 46 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这个解决方案适合你吗?让我知道,以便它也能帮助别人。谢谢 –

相关问题