2012-05-17 26 views
28

我想寫一個javascript函數,該函數返回HTML內容作爲給定函數的URL的字符串。我在Stackoverflow上找到了類似的答案。將HTML內容作爲字符串返回給定URL。 Javascript函數

我想用this answer來解決我的問題。

但是,好像document.write()不寫任何東西。當我加載頁面時,我得到一個空白屏幕。

<html> 
<head> 
</head> 
<body> 
    <script type="text/JavaScript"> 
    function httpGet(theUrl) 
    { 
    var xmlHttp = null; 

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("GET", theUrl, false); 
    xmlHttp.send(null); 
    return xmlHttp.responseText; 
    } 
    document.write(httpGet("https://stackoverflow.com/")); 
    </script> 
</body> 
</html> 
+5

使用.innerHT ML,而不是document.write。 –

+1

你的意思是像'httpGet(「http://stackoverflow.com/」).innerHTML;'?這也加載了一個空白頁。 –

+1

下面的答案描述你需要什麼。 –

回答

27

你需要返回的readyState == 4例如,當

function httpGet(theUrl) 
{ 
    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      return xmlhttp.responseText; 
     } 
    } 
    xmlhttp.open("GET", theUrl, false); 
    xmlhttp.send();  
} 
+0

我正在使用Chrome瀏覽器,並且控制檯錯誤顯示'Uncaught ReferenceError:xmlHttp未定義' –

+7

這是否會導致違反相同原則策略? :http://en.wikipedia.org/wiki/Same_origin_policy –

+0

@SoboLAN是的。 (至少對我而言) – Lerkes

8

你得到的迴應後,只是做調用這個函數來將數據添加到您的身體元素修飾

function createDiv(responsetext) 
{ 
    var _body = document.getElementsByTagName('body')[0]; 
    var _div = document.createElement('div'); 
    _div.innerHTML = responsetext; 
    _body.appendChild(_div); 
} 

@satya代碼如下

function httpGet(theUrl) 
{ 
    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      createDiv(xmlhttp.responseText); 
     } 
    } 
    xmlhttp.open("GET", theUrl, false); 
    xmlhttp.send();  
} 
17

唯一一個我發現對於跨站點,是這樣的功能:

<script type="text/javascript"> 
var your_url = 'http://www.example.com'; 

</script> 

<script type="text/javascript" src="jquery.min.js" ></script> 
<script type="text/javascript"> 
// jquery.xdomainajax.js ------ from padolsey 

jQuery.ajax = (function(_ajax){ 

    var protocol = location.protocol, 
     hostname = location.hostname, 
     exRegex = RegExp(protocol + '//' + hostname), 
     YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?', 
     query = 'select * from html where url="{URL}" and xpath="*"'; 

    function isExternal(url) { 
     return !exRegex.test(url) && /:\/\//.test(url); 
    } 

    return function(o) { 

     var url = o.url; 

     if (/get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url)) { 

      // Manipulate options so that JSONP-x request is made to YQL 

      o.url = YQL; 
      o.dataType = 'json'; 

      o.data = { 
       q: query.replace(
        '{URL}', 
        url + (o.data ? 
         (/\?/.test(url) ? '&' : '?') + jQuery.param(o.data) 
        : '') 
       ), 
       format: 'xml' 
      }; 

      // Since it's a JSONP request 
      // complete === success 
      if (!o.success && o.complete) { 
       o.success = o.complete; 
       delete o.complete; 
      } 

      o.success = (function(_success){ 
       return function(data) { 

        if (_success) { 
         // Fake XHR callback. 
         _success.call(this, { 
          responseText: data.results[0] 
           // YQL screws with <script>s 
           // Get rid of them 
           .replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '') 
         }, 'success'); 
        } 

       }; 
      })(o.success); 

     } 

     return _ajax.apply(this, arguments); 

    }; 

})(jQuery.ajax); 



$.ajax({ 
    url: your_url, 
    type: 'GET', 
    success: function(res) { 
     var text = res.responseText; 
     // then you can manipulate your text as you wish 
     alert(text); 
    } 
}); 

</script> 
+2

我總是將響應文本數據結果作爲0並引發異常。 – Kurkula

相關問題