2014-01-15 85 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來完成的。

相關問題