将HTML文件内容加载到Div [不使用iframe] [英] Load HTML File Contents to Div [without the use of iframes]

查看:157
本文介绍了将HTML文件内容加载到Div [不使用iframe]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很确定这是一个常见问题,但我对JS很新,并且遇到了一些麻烦。



我想加载x .html转换为ID为y的div,而不使用iframe。我已经尝试了一些东西,四处搜寻,但我找不到适合我的问题的体面解决方案。



如果可能,我更喜欢JavaScript中的某些内容。

在此先感谢大家!

解决方案

框架 - 促销答案你会认为这是JavaScript变得非常困难。它不是真的。

  var xhr = new XMLHttpRequest(); 
xhr.open('GET','x.html',true);
xhr.onreadystatechange = function(){
if(this.readyState!== 4)return;
if(this.status!== 200)return; //或任何你想要的错误处理
document.getElementById('y')。innerHTML = this.responseText;
};
xhr.send();如果您需要IE< 8兼容性,请首先执行此操作以使这些浏览器加速:

$ b 如果(window.XMLHttpRequest&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&) {
返回新的ActiveXObject('MSXML2.XMLHttp');
};
}

请注意,使用脚本将内容加载到页面中会使内容对客户端不可见没有JavaScript可用,例如搜索引擎。小心使用,并考虑服务器端包括,如果你只想把数据放在一个共同的共享文件中。


I'm quite sure this a common question, but I'm pretty new to JS and am having some trouble with this.

I would like to load x.html into a div with id "y" without using iframes. I've tried a few things, searched around, but I can't find a decent solution to my issue.

I would prefer something in JavaScript if possible.

Thanks in advance, everyone!

解决方案

Wow, from all the framework-promotional answers you'd think this was something JavaScript made incredibly difficult. It isn't really.

var xhr= new XMLHttpRequest();
xhr.open('GET', 'x.html', true);
xhr.onreadystatechange= function() {
    if (this.readyState!==4) return;
    if (this.status!==200) return; // or whatever error handling you want
    document.getElementById('y').innerHTML= this.responseText;
};
xhr.send();

If you need IE<8 compatibility, do this first to bring those browsers up to speed:

if (!window.XMLHttpRequest && 'ActiveXObject' in window) {
    window.XMLHttpRequest= function() {
        return new ActiveXObject('MSXML2.XMLHttp');
    };
}

Note that loading content into the page with scripts will make that content invisible to clients without JavaScript available, such as search engines. Use with care, and consider server-side includes if all you want is to put data in a common shared file.

这篇关于将HTML文件内容加载到Div [不使用iframe]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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