JavaScript实现获取远程的html到当前页面中
html代码
javascript代码
functionclientSideInclude(id,url){ varreq=false; //Safari,Firefox,及其他非微软浏览器 if(window.XMLHttpRequest){ try{ req=newXMLHttpRequest(); }catch(e){ req=false; } }elseif(window.ActiveXObject){ //ForInternetExploreronWindows try{ req=newActiveXObject("Msxml2.XMLHTTP"); }catch(e){ try{ req=newActiveXObject("Microsoft.XMLHTTP"); }catch(e){ req=false; } } } varelement=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对象。这个网页的显示要求"+ "InternetExplorer5以上版本,"+ "或Firefox或Safari浏览器,也可能会有其他可兼容的浏览器存在。"; } } clientSideInclude(includeHtml,"http://XXXXX.html");//页面中的一个div的id为includeHtml
用法很简单,代码里已经注释了,这里在简单描述下,给那些不看注释的人看吧
js代码在当前页面加载或者做成js文件加载进来,然后远端的代码会自动写入到当前页面里id号为includehtml的DIV里面