Chris Hillman
Chris Hillman

Reputation: 65

JSON feed display on a website

Im trying to get a JSON feed be loaded on a website I'm working on. I've looked around online, and there seems to be plenty of examples, but little information on how to return a remote webpage's JSON as a object.

Currently I have the below test code I'm working on.

The JSON feed I'm trying to get into my webpage is; http://www.wowprogress.com/guild/us/frostmourne/Group+Therapy/rating.tier13_10/json_rank

Current goal is just to view the returned JSON feed so I know its working, so I have been playing with the below snippet.

<html>
<title></title>
<head>
<script type="text/javascript">
    var xhttp = new XMLHttpRequest();       
var wowprogress
//var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); // Commented out currently, use for IE
xhttp.open("GET","http://www.wowprogress.com/guild/us/frostmourne/Group+Therapy/rating.tier13_10/json_rank",false);
xhttp.send();

var myJSONString = xhttp.innerTEXT;
alert(myJSONString);    

var myObject = eval("(" + myJSONString + ")");
var myValue = myObject.realm_rank;
    alert(myValue);

    </script>
    </head>
    <body>
    </body>
    </html>

any help would be greatly appreciated, or the right direction to investigate further.

Thanks :)

Upvotes: 1

Views: 474

Answers (2)

keeganwatkins
keeganwatkins

Reputation: 3686

i think you're running into cross-domain issues. browsers by default don't allow you to use XHR (ajax) to fetch documents that are located on a different domain than the host page (this also includes sub-domains).

there are some workarounds:

  • CORS : This is likely not an option, as it requires configuration on a server that you don't own

  • JSON-P : This may be an option, if the remote server understands it. It is essentially a JSON response wrapped in a function call, so that you can include it on your page as plain JS.

  • Proxy : create a proxy on the server so that you can make ajax requests to the same domain. Ben Alman has a simple example here.

in short, you are going to need another transport mechanism to be able to load remote documents on to your page via JS.

i hope that helps! cheers.

Upvotes: 1

austincheney
austincheney

Reputation: 1115

First, never use eval. Its horribly insecure.

Instead use JSON.parse(your_json) to convert your data into an object literal. When you are done with it and want to package it for transport then JSON.stringify(your_json);

Upvotes: 1

Related Questions