如何包含外部html(如果存在),否则什么也不做? [英] How to include external html if exists, else do nothing?

查看:54
本文介绍了如何包含外部html(如果存在),否则什么也不做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jquery的页面,我想检测是否存在外部文件.如果可以,我想将其加载到div中,但是如果不这样做,则我不希望其执行任何操作.

I have a page that uses jquery and I want to detect if an external file exists. If it does, I want to load it into a div, but if it doesn't, I want it to do nothing.

我正在使用此代码,它可以加载文件,但是如果外部文件不存在,它将加载404错误页面.我是jquery的新手,将不胜感激.另外,用于检查文件的方法还必须具有rootdomain +,以便可以将代码插入无需编辑的多个站点中.

I'm using this code and it works to load the file, but it's loading a 404 error page if the external file does not exist. I am very new at jquery and would appreciate any help. Also, the method to check for the file needs to have rootdomain+ so that the code can be plugged into multiple sites with no edits.

$(function() {
      $('#test').load('/pages/test.html');
});

任何帮助将不胜感激.我一直在搜索几天,但是我发现的唯一的东西就是头部检查脚本,如果url无效,则无法选择不执行任何操作.我很想知道自己如何编写这个简单的代码,但是现在它已经超出了我的脑海. :)

Any help would be greatly appreciated. I've been searching for days but the only things I have found are head check scripts that don't have the option of doing nothing if the url isn't valid. I would love to know how to write this simple code myself but right now it's over my head. :)

杰里

推荐答案

尝试使用ajax()方法而不是load(),并在成功回调中设置html():

Try using the ajax() method rather than load() and set your html() in the success callback:

$(function() {
    $.ajax({
        url: "/pages/test.html",
        cache: false,
        dataType: "html",
        success: function(html){
            $('#test').html(html);
        }
    });
});

这篇关于如何包含外部html(如果存在),否则什么也不做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆