0

在页面上,我有一个带有某个图像作为背景 URL 的 css 属性。

我想要发生的是通过 jquery/ajax 加载第二个(远程)图像(到 background-url 属性中),如果在检索图像时出现任何错误,则加载第二个“默认”图像。

我将如何完成这样的事情?

非常感谢!

4

2 回答 2

0
        $(document).ready(function() {
          // Handler for .ready() called.
            $.ajax({
                    url: "/loadimageurl.php",
                    type: "post",
                    data: data,
                    // callback handler that will be called on success
                    success: function(imageUrl, textStatus, jqXHR){
                        // log a message to the console
                        console.log("Hooray, it worked! Load The Image Here");
                        $('body').css('background-image', 'url(' + imageUrl + ')');
                    },
                    // callback handler that will be called on error
                    error: function(jqXHR, textStatus, errorThrown){
                        DefaultimageUrl = 'path/to/default/image.jpg';                        
                        // log the error to the console
                        console.log(
                            "Load Default Image here! The following error occured: "+
                            textStatus, errorThrown
                        );
                        $('body').css('background-image', 'url(' + DefaultimageUrl + ')');
                    }
                });


        });

当页面加载时,ajax 调用将被触发并被loadimageurl.php调用。如果需要,数据变量将数据发布到 php 脚本。如果调用成功(从 php 脚本返回图像 url)您设置图像 url 否则错误函数将设置默认图像 url。

阅读注释以正确理解步骤并使用控制台检查 ajax 调用的执行方式并返回数据。如果您有任何问题,请告诉我。

于 2012-12-29T04:10:36.557 回答
0

这是我能够想出的:

$(function() {
    var main_image = '';
    var second_image = '';
    $.ajax({url: main_image, cache: false, success: function(d) {
        console.log('success');
        $('#bg').css('background',main_image);                
    }, error: function() {
        console.log('failure');
        $('#bg').css('background',second_image);
    }});    
});​ 

jsFiddle:http: //jsfiddle.net/sVZdK/

我无法用图像对其进行测试,但我相信它会起作用。

于 2012-12-29T04:14:56.753 回答