JS或JQuery獲取頁面數據的跨域問題


JS或JQuery獲取頁面數據存在着跨域問題。

比如要用JQuery 如果跨域獲取數據 只能獲取 返回json格式 的數據
1、使用$.getJSON方法,可以跨域獲取json格式的數據
2、使用$.ajax方法,並且設置type為GET,dataType為jsonp

$.ajax 是沒法直接 獲取 遠程網頁源代碼,因為存在跨域問題。

你可以這么做:

本地新增一個服務端的頁面:
如 ServerGetData.asp, ServerGetData.aspx, ServerGetData.php, ServerGetData.jsp ...
讓服務端頁面獲取數據(他們可以獲取遠程網頁源代碼)
比如php代碼:
 $file = file_get_contents('http://www.baidu.com/');
 echo($file);
然后 用 $.ajax 或 $.get 即可

曾想到iframe引入數據再用js獲取,可調試的時候同樣發現避免不了跨域問題。

View Code
<html>
<head>
<meta http-equiv="contentType" content="text/html;charset=utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>
$(function(){
        /*
        var iframe = document.createElement("iframe");
        iframe.src = "http://www.baidu.com/index.php";
        if (iframe.attachEvent){
           iframe.attachEvent("onload", function(){
               alert("loaded");
            });} else {
            iframe.onload = function(){
                alert("loaded");
            };
        }
        */

        var if_w = $("body").width();
        var if_h = $(window).height();
        //var if_w = 800, if_h = 800;
        //$("<iframe width='" + if_w + "' height='" + if_h + "' id='iframe1' style='z-index:-1'></iframe>").prependTo('body');
        $("<iframe width='" + if_w + "' height='" + if_h + "' id='iframe1' style='display:none;z-index:-1'></iframe>").appendTo('body');
        $("#phone").change(function(){
            $("#message").text("正在加載..");
            $("#iframe1").attr("src",$(this).val());
        });

        $("#iframe1").load(function(){
            $("#message").text("載入完畢");
            //alert($("#iframe1").contents().html());
            //alert($(document.getElementById('iframe1').contentWindow.document.body).html());
            //alert($(window.frames["iframe1"].document).html());
            var win = document.getElementById('iframe1').contentWindow;
            var html = win.document.body.innerHTML;
            alert(html);

        });
});
</script>
</head>
<body>
<select id="phone">
<option value="about:blank">請選擇</option>
<option value="http://www.baidu.com/">baidu</option>
<option value="http://www.sogou.com/">sogou</option>
<option value="http://www.youdao.com/">youdao</option>
</select>
<span id="message" style="color:green"></span>
<hr/>
<!--
<iframe id="iframe1" src="" width="600" height="700"></iframe>
-->
</body>
</html>

JS獲取整個頁面文檔的實現代碼:

View Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<div id="test">
<pre>
休息休息
</pre>
</div>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript">
var connector = (function(){
var connector = null;
if(window.XMLHttpRequest){
connector = new XMLHttpRequest();
}else if(window.ActiveXObject){
connector = new ActiveXObject('Microsoft.XMLHTTP');
}
return connector;
})();
var innerText = document.body.innerText ? 'innerText' : 'textContent';
var handler = function(response){
document.getElementById('test').getElementsByTagName('pre')[0][innerText] = response;
}
connector.onreadystatechange = (function(callback){
return function(){
if(connector.readyState == 4){//這里connector.status == 200都省了。
callback.call(connector,connector.responseText);
}
}
})(handler);
connector.open('GET','aa.html',true);//發送到本頁面
connector.send();
</script>
</body>
</html>

遠程網頁源代碼讀取:

View Code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>遠程網頁源代碼讀取</title>

<style type="text/css">
/* 頁面字體樣式 */
body, td, input, textarea {
    font-family:Arial;
    font-size:12px;
}
</style>

<script type="text/javascript">
//用於創建XMLHttpRequest對象
function createXmlHttp() {
    //根據window.XMLHttpRequest對象是否存在使用不同的創建方式
    if (window.XMLHttpRequest) {
       xmlHttp = new XMLHttpRequest();                  //FireFox、Opera等瀏覽器支持的創建方式
    } else {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE瀏覽器支持的創建方式
    }
}

//直接通過XMLHttpRequest對象獲取遠程網頁源代碼
function getSource() {
    var url = document.getElementById("url").value;             //獲取目標地址信息

    //地址為空時提示用戶輸入
    if (url == "") {
        alert("請輸入網頁地址。");
        return;
    }

    document.getElementById("source").value = "正在加載……";   //提示正在加載
    createXmlHttp();                                            //創建XMLHttpRequest對象
    xmlHttp.onreadystatechange = writeSource;                   //設置回調函數
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
}

//將遠程網頁源代碼寫入頁面文字區域
function writeSource() {
    if (xmlHttp.readyState == 4) {
        document.getElementById("source").value = xmlHttp.responseText;
    }
}
</script>
</head>

<body>
<h1>遠程網頁源代碼讀取</h1>

<div>
    地址:<input type="text" id="url">
    <input type="button" onclick="getSource()" value="獲取源碼">
</div>

<textarea rows="10" cols="80" id="source"></textarea>

</body>
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM