简体   繁体   中英

XMLHttpRequest responseText is empty

I have read much on this site, but I can't solve my problem! :( It must be very easy but it does not work!

The problem is http.responseText is empty.

I'm using the webspace on http://www.000webhost.com

Is it posible to get a String with the Sourcecode of www.google.de ?

Thanks for any help!

<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>

its not possible with ajax because of same origin policy , but to solve your problem you can use server side programming like PHP or Nodejs. basically PHP will be available in web hostings.

create 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;    
  ?>

use your javascript as below

  <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>

Hope this solves your problem. Cheers

Making client side http requests is limited by the browser to only allowing requests from the same server that supplied the original page. This is what is being referred to as the Same Origin Policy.

As mentioned by others, this is normally done by requesting the URL in your server side code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM