Issue with JSON.parse() from URL

时间:2018-07-25 05:00:31

标签: javascript json html5 xml-parsing bloomberg

I have this code trying to obtain prices from Bloomberg but I can't make it works.

This is the URL:

https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15

And my failure code:

<p id="quote"></p>

<script>
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var price= JSON.parse(this.responseText);
            document.getElementById("quote").innerHTML = price[0]["previousClosingPriceOneTradingDayAgo"];
        }
    };
    xmlhttp.open("GET", "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15&currency=MXN", true);
    xmlhttp.send();
</script>

Thanks in advance.

3 个答案:

答案 0 :(得分:0)

What is the excat error message your getting? Is it something like "No 'Access-Control-Allow-Origin' header is present on the requested resource"?

If so, that has nothing to do with JSON.parse as it is a security measure against XSS (Cross Site Scripting). You cannot request web responses from other domains if the server doesn't allows it explicitly.

See https://en.wikipedia.org/wiki/Cross-origin_resource_sharing for more information.

As an additional note: you can work around this. Even if you have no access to the server you could make use of a proxy server, that gets the request for you and uses the appropriate response header to allow your script to make the response. An example would be "corsproxy" from npm (No experience with it. Just a quick google search).

答案 1 :(得分:0)

You can get value as below by adding jQuery to your project

$.ajax({
    type: "GET",
    url: "https://www.bloomberg.com/markets2/api/intraday/BACHOCOB:MM?days=1&interval=2&volumeInterval=15",
    dataType: "json",
    success: function(getPrice) {
        $('#quote').append(getPrice[0].previousClosingPriceOneTradingDayAgo);
    }
});

答案 2 :(得分:0)

It seems CORS is an issue. Since you are using GET request to an SSL URL, it expects you to send this request from an HTTPS origin. To test your script, use Chrome Browser with CORS extension installed. You shall see the result.

In short, you need an HTTPS origin URL, you might want to try CURL with PHP for a possible solution if SSL is an issue !