以下代码已测试。记录在此,做个备忘。
加载Js:
function LoadJs(newJS)//newJS为服务器js文件名
{
var scp = document.createElement("script");
scp.src = newJS;
scp.type = "text/javascript";
document.body.appendChild(scp);
}
加载网页:
function LoadPage(url,func) //url为任意服务器文件名
{
var xhr= new XMLHttpRequest();
xhr.open("GET", url,true); //true:异步模式,false:同步模式
//异步模式注册回调函数
xhr.onreadystatechange = function() {
if(xhr.readyState ==4 && ((xhr.status>=200&&xhr.status<300)||xhr.status==304)){ //304代表页面无修改可以使用本地缓存
func(xhr.responseText); //自定义func函数来处理接收的内容
}
};
xhr.send(null);
//同步模式直接使用返回数据
//func(xhr.responseText);
}
也可以用LoadPage来加载js,只要把func指定为eval即可。