js/jQuery-获得其他页面内容-1.2

方法一 使用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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值