使用jQuery和AJAX定期更改背景图像src

I'm trying to have the background image of the body of my page change every (approximatly) N seconds. For this i have a PHP function that echoes random image src when i call it using AJAX. I then replace the current body background image src by this newly generated one, but i can't get it to work.

Here is the code, is there anything wrong in it ?

(function($) {

    var $body = $('body');

    window.setInterval(function() {
        $.ajax({
            url: 'http://localhost/some_path/index.php?exec=getNewBkgImgSrc',
        }).done(function(data) {
            var newImage = new Image();
            newImage.onload = function() {
                $body.css('background-image', newImage.src);
            };
            newImage.src = data;
        });
    }, 5000);

})(window.jQuery);

And the PHP function which does work :

public function getNewBkgImgSrc() {
    echo CONTENT_URL_DIR.'/Wallpapers/wallpaper ('.rand(1, 20).').jpg';
}

Could this be because i'm using localhost ? I can mremeber having AJAX problems before when i was developping locally.

EDIT : A clue maybe is that the style property of the body element doesn't sseem to change / be set in Firebug. I also tried $('body').first() and $(document.body) and using url("") (in the value of background-image property) but it doesn't work either. The onload event does fire however.

Thanks for your help.

Why are you creating a new image object if you are getting a URL back from PHP? Just set the background-image property of body to:

$body.css('background-image', "url('" + data + "')");

If using vanilla JS:

document.body.style.backgroundImage="url('" + data + "')";

See proper format for that property here: http://www.w3schools.com/cssref/pr_background-image.asp

might need to cache bust the ajax call. Try changing the url property of the ajax call to '/some_path/index.php?exec=getNewBkgImgSrc&cb='+((new Date).getTime()).

I have not good sense about var $body = $('body');

use $('body').css('background-image', newImage.src);