How can I process JSON data in JQuery, that's being returned with a header type of “text/html”?

寵の児 提交于 2019-12-13 01:27:55

问题


I'm trying to use the jquery, getJSON method to get JSON data from a public API. I keep getting the following errors when the callback of my getJSON request executes.

Warning: Resource interpreted as Script but transferred with MIME type text/html

Error: Uncaught SyntaxError: Unexpected token :

I've inspected the header of the response and, sure enough, it is set to text\html. Since this is a public API that I can't control, how can I easily request and parse this JSON data?

For reference, the link below is the link to the JSON data that I am trying to acquire.

JSON Request (http://bitcoincharts.com/t/weighted_prices.json)


回答1:


If you can't control the mime type, use jQuery.ajax instead of jQuery.getJSON. Then in the success callback you can do something like this:

jQuery.ajax({
    dataType: "text", //you may need this.
    success: function(data, textStatus, jqXHR) {
        var jsonData = JSON.parse(data);
        ....
    }
});

Another thing you could try is:

jQuery.ajax({
    dataType: "json",
    success: function(data, textStatus, jqXHR) {
        //data here will be a JavaScript object
        ....
    }
});

Although I'm not sure if jQuery will complain if the mime type doesn't match. It's worth a shot though.

EDIT: On another note, how are you able to access that data from your script? Even though it's a public API, it's on another server and so that will violate the same-origin policy. When I do the following:

jQuery.getJSON("http://bitcoincharts.com/t/weighted_prices.json", function(data) {
    console.log(data);
});

From my Chrome console, I see the following error:

XMLHttpRequest cannot load http://bitcoincharts.com/t/weighted_prices.json?_=1346263039525. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.

You have to see if BitCoin Charts supports a JSONP alternative. Otherwise, your only option is to set up something on the server-side that grabs this data for you and returns it back to you in JSON with the correct mime-type.



来源:https://stackoverflow.com/questions/12183402/how-can-i-process-json-data-in-jquery-thats-being-returned-with-a-header-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!