XMLHttpRequest responseText为空

时间:2014-01-15 16:29:33

标签: javascript xmlhttprequest

我在这个网站上看了很多,但我无法解决我的问题! :( 它一定很容易但不起作用!

问题是http.responseText为空。

我正在使用http://www.000webhost.com

上的网站空间

获取源代码为www.google.de的字符串是否可行?

感谢您的帮助!

<html> 
<title>Test Site</title>
<body>
<h1>My Example</h1>
<script type="text/javascript">

var http = new XMLHttpRequest();

http.open("GET", 'https://www.google.de', true);
http.send(null);

http.onreadystatechange = function() {
    alert(http.responseText);
}

alert("The end is reached");
</script> 


<b>Here is some more HTML</b> 
</body>
</html>

2 个答案:

答案 0 :(得分:1)

由于相同的原始策略,它不可能与ajax,但为了解决您的问题,您可以使用服务器端编程,如PHP或Nodejs。基本上PHP将在网络托管中提供。

创建getGoogle.php

 <?php 
    // create curl resource 
    $ch = curl_init(); 

    // set url 
    curl_setopt($ch, CURLOPT_URL, "www.google.de"); 

    //return the transfer as a string 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    // $output contains the output string 
    $output = curl_exec($ch); 

    // close curl resource to free up system resources 
    curl_close($ch);  

    echo $output;    
  ?>

使用您的javascript如下

  <script type="text/javascript">

  var http = new XMLHttpRequest();

   http.open("GET", 'getGoogle.php', true);
   http.send(null);

   http.onreadystatechange = function() {
        alert(http.responseText);
   }

   alert("The end is reached");
   </script>

希望这能解决您的问题。干杯

答案 1 :(得分:0)

使客户端http请求受到浏览器的限制,仅允许来自提供原始页面的同一服务器的请求。这就是所谓的同源政策。

正如其他人所说,这通常是通过在服务器端代码中请求URL来完成的。

相关问题