??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 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: