方法一 使用load加载
$('#mainDiv').load(href);//mainDiv是被追加的div,href是页面的名称
方法二 使用ajax
这个思维理论简单,ajax请求页面数据,然后把数据追加到页面
$.ajax({
type: "GET",
url: href,
dataType:'html',
success: function(data) {
$('#mainDiv').html(data);
}
});
注:这种方式存在问题,跨域时候会请求失败。
所以我们需要用jsonp的方式进行跨域
function doCrossDomainAjax(data, url){
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
dataType: 'jsonp', //必须写
crossDomain: true, //必须写
headers: {
'Access-Control-Allow-Origin': '*' //加头部
},
contentType: "application/json",
success: function(data) {
alert('ok');
}
});
}
注:1.90.版本后使用method而不是type确定请求方式
方法三 使用XMLHttpRequest,自定义方法获得页面
///根据url发送请求
///url: 请求路径
function makeCorsRequest(url, callbackFunction) {
var xmlHttp = new XMLHttpRequest();
//设置跨域访问请求对象
if ("withCredentials" in xmlHttp) {
// "withCredentials"属性是XMLHTTPRequest2中独有的
xmlHttp.open('GET', url, true);
} else if (typeof XDomainRequest != "undefined") {
// 检测是否XDomainRequest可用
xmlHttp = new XDomainRequest();
xmlHttp.open('GET', url);
} else {
alert('抱歉,不支持CORS');
return;
}
//设置计时器,防止超时
var timedout = false;
var timer = setTimeout(function () {
timedout = true;
xmlHttp.abort();
}, 5000);
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState != 4) { return; }
if (timedout) { return; }
clearTimeout(timer);
if (xmlHttp.status === 200) {
callbackFunction(xmlHttp.responseText);
}
if (xmlHttp.status === 404) {
alert("路径请求错误");
}
};
xmlHttp.onerror = function () {
alert('抱歉,请求错误');
};
xmlHttp.send();
}