Question

I want to retrieve information from my Stack Overflow profile as JSON using the API.

So I use this link http:/api.stackoverflow.com/1.0/users/401025/.

But when I make the request I get a file containing the JSON data. How do I deal with that file using Ajax?

Here is my code (http://jsfiddle.net/hJhfU/2/):

<html>
 <head>
  <script>
   var req;

   getReputation();

   function getReputation(){
      req = new XMLHttpRequest();
      req.open('GET', 'http://api.stackoverflow.com/1.0/users/401025/');
      req.onreadystatechange = processUser;
      req.send();
   }

   function processUser(){       
       var res = JSON.parse(req.responseText);
       alert('test');      
   }
  </script>
 </head>

The alert is never fired and req.responseText seems to be empty. Any ideas?

Was it helpful?

Solution

Note: You cannot use Ajax to access another domain. (This is called the same-domain policy.)

However, the StackOverflow API supports JSONP callbacks, so here is a solution:

Load in the script via a <script> tag.

Create a function that does just that:

function load_script(src) {
   var scrip = document.createElement('script');
   scrip.src = src;
   document.getElementsByTagName('head')[0].appendChild(scrip);
   return scrip; //just for the heck of it
}

Set up the callback function:

function soResponse(obj) {
   alert(obj.users[0].reputation);
}

Load it!

load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top