??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.

    评论

报告相同问题?

悬赏问题

  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误
  • ¥100 反编译微信小游戏求指导
  • ¥15 docker模式webrtc-streamer 无法播放公网rtsp