2012-05-17 32 views
28

Tôi muốn viết một hàm javascript trả về nội dung HTML dưới dạng chuỗi cho URL vào hàm. Tôi tìm thấy một câu trả lời tương tự trên Stackoverflow.Trả lại nội dung HTML dưới dạng chuỗi, cho trước URL. Chức năng Javascript

Tôi đang cố gắng sử dụng this answer để giải quyết vấn đề của mình.

Tuy nhiên, có vẻ như là document.write() không viết gì cả. Khi tôi tải trang, tôi nhận được một màn hình trống.

<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

Sử dụng .innerHT ML, không phải document.write. –

+1

Bạn có nghĩa là 'httpGet (" http://stackoverflow.com/ ") .innerHTML;'? Điều này cũng tải một trang trống. –

+1

Các câu trả lời dưới đây mô tả những gì bạn cần. –

Trả lời

27

bạn cần phải trả lại khi readyState == 4 ví dụ

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

Tôi đang sử dụng Chrome và lỗi giao diện điều khiển có nội dung 'Tham chiếu không bắt buộcLỗi: xmlHttp không được xác định' –

+7

Điều này sẽ không gây ra vi phạm Chính sách gốc không? : http: //en.wikipedia.org/wiki/Same_origin_policy –

+0

@SoboLAN Đúng vậy. (Ít nhất là đối với tôi) – Lerkes

8

sau khi bạn nhận được câu trả lời chỉ làm gọi chức năng này để nối thêm dữ liệu vào phần cơ thể của bạn

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

đang @satya sửa đổi như sau

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

Là người duy nhất tôi đã tìm thấy cho Cross-site, là chức năng này:

<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

Tôi luôn nhận được kết quả dữ liệu văn bản phản hồi là 0 và ném ngoại lệ. – Kurkula

Các vấn đề liên quan