Get JSON using the StackOverflow API

I want to get information from my profile as JSON using the API.

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

But when I make a request, I get a file containing JSON data. How can I handle this 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> 

A warning never fires and req.responseText seems empty. Any ideas?

+6
javascript ajax stackexchange-api
source share
1 answer

Note. You cannot use Ajax to access another domain. (This is called a single domain policy .)

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

Download the script using the <script> .

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); } 

Download it!

 load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse'); 
+8
source share

All Articles