当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript实现获取远程的html到当前页面中

JavaScript实现获取远程的html到当前页面中

2019年03月20日  | 移动技术网IT编程  | 我要评论

html代码

<div id="includehtml"></div>

javascript代码

function clientsideinclude(id, url) {
  var req = false;
  // safari, firefox, 及其他非微软浏览器
  if (window.xmlhttprequest) {
    try {
      req = new xmlhttprequest();
    } catch (e) {
      req = false;
    }
  } else if (window.activexobject) {

    // for internet explorer on windows
    try {
      req = new activexobject("msxml2.xmlhttp");
    } catch (e) {
      try {
        req = new activexobject("microsoft.xmlhttp");
      } catch (e) {
        req = false;
      }
    }
  }
  var element = document.getelementbyid(id);
  if (!element) {
    alert("函数clientsideinclude无法找到id " + id + "。" +
      "你的网页中必须有一个含有这个id的div 或 span 标签。");
    return;
  }
  if (req) {
    // 同步请求,等待收到全部内容
    req.open('get', url, false);
    req.send(null);
    if (req.status == 404) {
      clientsideinclude(id, 'error.html')
    } else {
      element.innerhtml = req.responsetext;
    }
  } else {
    element.innerhtml =
      "对不起,你的浏览器不支持" +
      "xmlhttprequest 对象。这个网页的显示要求" +
      "internet explorer 5 以上版本, " +
      "或 firefox 或 safari 浏览器,也可能会有其他可兼容的浏览器存在。";
  }
}

clientsideinclude(includehtml, "http://xxxxx.html");//页面中的一个div的id为includehtml

用法很简单,代码里已经注释了,这里在简单描述下,给那些不看注释的人看吧

js代码在当前页面加载或者做成js文件加载进来,然后远端的代码会自动写入到当前页面里id号为 includehtml的div里面

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网