tags:

views:

67

answers:

3

i have a php function which returns a random json encoded color

<?php
    function randNum() {
        return rand(0, 255);
    }

    $color = array ('r'=>randNum(),'g'=>randNum(),'b'=>randNum());
    echo json_encode($color);

?>

on the page i have a jquery function that whenever an event occurs, asks for a color and changes the window background accordingly

$('.wnd').mouseenter(function() {
    $.getJSON("color.php", function(color){
        var rgbString = 'rgb(' + color.r + ', ' + color.g + ', '+ color.b + ')';
        var hexString = rgb2hex(rgbString);
        $('.wnd').css('background-color', hexString);
    });
});

whis works good in ff3 and chrome, but in ie8 i always receive the same color. any idea why?

+3  A: 

IE is probably getting a cached version of the page. Pick your favorite method of requesting a fresh document and go with it :)

inerte
A: 

Your page is probably getting cached in IE, which has a more aggressive caching policy than other browsers. Instead of requesting color.php, try this:

$.getJSON("color.php?_" + new Date().getTime().toString(), function(color)...

This is the method that jQuery uses to prevent caching. You're just adding a unique parameter to the URL to fake the browser into thinking it's a totally new request.

Tim S. Van Haren
+1  A: 

As @inerte said, it's probably IE that caches the result.

You may want to use $.ajax and set the cache option to false, since it is false only for dataType script and jsonp:

$.ajax({
  type: "GET",
  url: "color.php",
  success: function (color) {
    var rgbString = 'rgb(' + color.r + ', ' + color.g + ', '+ color.b + ')',
        hexString = rgb2hex(rgbString);

    $('.wnd').css('background-color', hexString);
  },
  dataType: 'json',
  cache: false
})

Or you could set that option using $.ajaxSetup before using $.getJSON:

$.ajaxSetup({ cache: false });
CMS