??yy 2015-11-18 10:56 采纳率: 0%
浏览 18

ajax-查看是否存在2个URL

what I have at the minute works for the first URL test, however, I don't know how to get it to test the second URL, should the first one not exist.

    var str = document.title.replace(/ | My Site/i, '');
    var title = str.replace(/ /g, '-');
    var finish = title.toLowerCase();
    var banner = finish.split('-', 1)[0]
    var address = "http://example.com/images/" + finish + ".jpg";
    var banneraddress = "http://example.com/images/" + banner + "-banner.jpg";
    $.ajax({
        type: 'HEAD',
        url: address,
            success: function() {
                // Primary URL exists
                document.getElementById("TRY").src = address;
            },
            error: function() {
                $.ajax({
                type: 'HEAD',
                url: banneraddress,
                    success: function() {
                        // Secondary URL exists
                        document.getElementById("TRY").src = banneraddress;
                    },
                    error: function() {
                        // Both failed
                        null
                    }
                });
            }
    });

What needs to happen is if the user loads a page and /images/page-title.jpg exists, it will add that src to the the images with the ID "TRY".

If that test fails, if /images/page-banner.jpg exists add that src to the images

And, for now, if neither work do nothing.

  • 写回答

1条回答 默认 最新

  • weixin_33691700 2015-11-18 11:08
    关注

    Just move your AJAX logic to separate function, later you can ask the function if both images exists, and if they, you can change the src attribute of your image.

    E.g.

    if( checkIfImageExists(address) && checkIfImageExists(banner_address) ) {
        // both images exists, change src attribute
    } else {
        // both images do not exists, do something else
    }
    

    You should modify your success and error callbacks to return true or false.

    评论

报告相同问题?