-1

Im trying to grab the url of the img in the XML file of the daily bing photo so i can set it as the src of my websites background.

This is my code:

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>

<script>
    var x = new XMLHttpRequest();
    x.open("GET", "http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US", true);
    x.onreadystatechange = function () {
        if (x.readyState == 4 && x.status == 200) {
            var doc = x.responseXML;
            var stock = document.getElementById("stock");
            var img = doc.getElementsByTagName("url")[0].childNodes[0].nodeValue;
            stocksrc.setAttribute("src", img);
        }
    };
    x.send(null);
</script>

</head>
<body>
    <img id="stock" src="#">
</body>
</html>

This is the error im having:

XMLHttpRequest cannot load http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Bogdan Bogdanov
  • 1,707
  • 2
  • 20
  • 31
Intellz
  • 11
  • 2

1 Answers1

0

You cannot do XHR requests from one domain (abc.com) to another (xyz.com) unless the xyz.com explicitly allows abc.com to do so.

As bing.com have not explicitly allowed you to do cross domain requests (ie, they have not included the appropriate Access-control-allow-origin header), browsers will prevent you from loading that resource from your own website.

See: https://stackoverflow.com/a/10636765/260035 for more

Community
  • 1
  • 1
Dal Hundal
  • 3,234
  • 16
  • 21