简体   繁体   中英

How to use javascript for http request using .com url?

So I want to make a website that loads certain html from other different websites, let's say google.com for example, using javascript. I've done this...

<button type="button" onclick="load()">Request data</button>
<p id="demo"></p>
<script>
function load() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
  if(xhttp.readyState === 4 && xhttp.status === 200){
      document.getElementById("demo").innerHTML = xhttp.responseText;
  };
}
xhttp.open("GET", "http://www.google.com or some .com url", true);
xhttp.send();
}
</script>

And it is not working. What am I missing? Anything is appreciated!

XMLHttpRequest will give you Same Origin Policy Error . You can overcome this by using script HTML tags to get data from another domain by doing something like this:

script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://www.google.com';

After this you will end up with

<script> 
  //Some Data
</script>

So, you will have to use JSONP instead. Example:

     <script>
        $(document).ready(function(){
            $.ajax({
                url: 'http://google.com/'
                dataType: 'jsonp',
                success: function(){
                    // Do something
                }, 
                error: function(){
                    // Do Something
                }
            });
        })
    </script>

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