2014-01-15 83 views
1

我已经在这个网站上阅读了很多,但是我无法解决我的问题! :( 它必须是很容易的,但它不工作!XMLHttpRequest responseText为空

问题是http.responseText是空的。

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

网络空间是不是更多钞票,以获得与一个String的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> 
+1

你不能用ajax下载其他人的东西,除非他们打开CORS来允许它。 – dandavis

+1

同源政策; https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript –

+0

如果您尝试向不同的域发出请求,请求返回为空(“Access-Control-Allow-Origin”) –

回答

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> 

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

+0

我用cURL试了一下! Google只是一个例子。我不能使用cURL couse我必须发布用户名和密码,它只会在CURLOPT_FOLLOWLOCATION = true的情况下工作!但webhoster安全模式enabeld所以cURL不是一个选项! :(我也许我可以用Javascript解决它。我认为CORS是不允许的,所以有没有办法从其他域获取信息?相信我我自3天以来一直在问googel。 – DarkMark

+0

您是否试图禁用安全模式使用.htaccess – Kishorevarma

+0

嘿我得到了curl错误的解决方案。使用这个代码http://pastie.org/7646116它有一个叫做“curl_exec_follow”的函数,你必须使用这个函数来代替curl_exec(用curl_exec_follow替换curl_exec ) – Kishorevarma

0

使浏览器限制客户端http请求只允许来自提供原始页面的相同服务器的请求。这就是所谓的“同源政策”。

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

相关问题