2012-05-17 11 views
28

Chcę napisać funkcję javascript, która zwraca treść HTML jako ciąg podany URL do funkcji. Znalazłem podobną odpowiedź na Stackoverflow.Powraca treść HTML jako ciąg znaków, podany adres URL. Funkcja JavaScript

Próbuję użyć this answer, aby rozwiązać mój problem.

Jednak wydaje się, że document.write() nic nie pisze. Kiedy ładuję stronę, dostaję pusty ekran.

<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

Użyj .innerHT ML, nie document.write. –

+1

Czy chodzi ci o 'httpGet (" http://stackoverflow.com/ ") .innerHTML;'? To również załadowało pustą stronę. –

+1

Poniższe odpowiedzi opisują, czego potrzebujesz. –

Odpowiedz

27

musisz wrócić, gdy np == 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

Używam Chrome, a błąd konsoli brzmi "Uncaught ReferenceError: xmlHttp nie jest zdefiniowany" –

+7

Czy to nie spowoduje naruszenia zasad tego samego pochodzenia? : http: //en.wikipedia.org/wiki/Same_origin_policy –

+0

@SoboLAN Tak, to robi. (Przynajmniej dla mnie) – Lerkes

8

Po uzyskaniu odpowiedzi tylko zrobić wywołać tę funkcję, aby dołączyć dane do elementu nadwozia

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

kod @satya zmodyfikowane jak poniżej

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

Tylko jeden znalazłem dla Cross-site, to ta funkcja:

<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

Zawsze otrzymuję wyniki danych tekstowych odpowiedzi jako 0 i zgłaszam wyjątek. – Kurkula

Powiązane problemy