[英]Ajax request doesn't work for mobile devices
I am so new for ajax and jquery! 我是ajax和jquery的新手!
At the below, my codes are working as a charm at desktop pc's. 在下面,我的代码作为桌面电脑的魅力。
I can collect the spent time for clients, but in mobile devices ajax request is not working. 我可以为客户收集花费的时间,但在移动设备中,ajax请求无效。
Here is my code: 这是我的代码:
<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>
It doesnt work for my phone (iphone)! 它不适用于我的手机(iphone)!
Anyone could help me out please? 有人可以帮帮我吗?
Thanks! 谢谢!
I think this problem was caused by the fact that mobile device don't support window.onbeforeunload
. 我认为这个问题是由移动设备不支持window.onbeforeunload
。 To have similar effect, try document.unload
or document.pagehide
要获得类似的效果,请尝试使用document.unload
或document.pagehide
Try this: 尝试这个:
<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>
This event will work for both browsers and iOS devices as well. 此事件也适用于浏览器和iOS设备。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.