简体   繁体   中英

AJAX and setTimeout on Internet Explorer

I'm trying to get the server datetime using ajax. I'm having a trouble running the script on Internet Explorer.


My old code was like this. (But it only displays client's pc datetime which can be changed anytime by the client)

var _current = new Date();
var _day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][_current.getDay()];
var _month = ["January","February","March","April","May","June","July","August","September","October","November","December"][_current.getMonth()]
var _date = _current.getDate(); if(_date < 10){_date = "0" + _date;}
var _year = _current.getFullYear();
var _hours = _current.getHours(); if(_hours > 12){_hours = _hours - 12; var ampm = "PM"}else{var ampm = "AM"}if(_hours < 10){_hours = "0" + _hours;}
var _minutes = _current.getMinutes(); if(_minutes < 10){_minutes = "0" + _minutes;}
var _seconds = _current.getSeconds(); if(_seconds < 10){_seconds = "0" + _seconds;}
$("#datetime").html("");
$("#datetime").html(_day + ", " + _month + " " + _date + ", " + _year + ", " + _hours + ":" + _minutes + ":" + _seconds + " " + ampm + "");

output: Wednesday, December 02, 2015, 11:47 AM (GMT+8)

So, I switched to AJAX and made a PHP page.

function getDateTime(){
    $.ajax({
        url: 'datetime.php',
        success:function(content){
            $("#datetime").html("");
            $("#datetime").append(content);
        }
    });
    window.setTimeout(getDateTime,1000);
}

php

<?php

// Set Timezone
date_default_timezone_set('Asia/Taipei');

// Display DateTime
echo date("l, F d, Y, h:i:s A",strtotime('Now'))."(GMT".date("O",strtotime('Now')).")";

?>

output: Wednesday, December 02, 2015, 11:47 AM (GMT+0800)

To me it looks like the issue with caching of the ajax call because the request URL will be same all the time. You can try

$.ajaxSetup({
    cache: false
});

This will add some random request query string and will break any caching issues, if any. May be worth a try.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM