日期:2014-05-16  浏览次数:20394 次

用XMLHTTPRequest获取网页源代码的疑问?
JScript code

function addLoadEvent(func){
    var oldonload=window.onload;
    if(typeof window.onload!='function'){
        window.onload=func;
    }else{
        window.onload=function(){
            oldonload();
            func();
        }
    }
}


addLoadEvent(doth);    


var READY_STATE_UNINITIALIZED=0;
var READY_STATE_LOADING=1;
var READY_STATE_LOADED=2;
var READY_STATE_INTERACTIVE=3;
var READY_STATE_COMPLETE=4;
            
var req=null;
var console=null;
            
             
function sendRequest(url,params,HttpMethod){
    if(!HttpMethod){
        HttpMethod="GET";
    }
    req=initXMLHTTPRequest();
    if(req){
        req.onreadystatechange=onReadyStateChange;
        req.open(HttpMethod,url,true);
        req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        req.setRequestHeader("Pragma", "no-cache");
        
        req.send(params);
    }
}

function initXMLHTTPRequest(){
        var xRequest=null;
    if(window.XMLHttpRequest){
        xRequest=new XMLHttpRequest();
    }else if(typeof ActiveXObject!="undefined"){
        xRequest=new ActiveXObject
        ("Microsoft.XMLHTTP");
    }
    return xRequest;
}

function onReadyStateChange(){
    var ready=req.readyState;
    check=req.readyState;
    var data=" ";
    if(ready==READY_STATE_COMPLETE){
        data=req.responseText;
        
    
    }
    toConsole(data);
}

function toConsole(data){
    if(console!=null){
        var newline=document.createElement("div");
        newline.id="comedata";
        console.appendChild(newline);
        var txt=document.createTextNode(data);
        newline.appendChild(txt);

        
    }
}

function doth(){
    console=document.getElementById('console');
    sendRequest("data.txt")
}





获取本地data.txt里的内容一切正常。
我将data.txt换成url为什么显示的结果是一片空白呢?

------解决方案--------------------
楼主参照下

http://blog.csdn.net/yixinpai/article/details/6045094
------解决方案--------------------
这个用后台做

参考下 
http://uicss.cn/cross-domain/