Hi,

I tried to retrieve information of my user profile on stackoverflow via the api using ajax/jquery. But it does not work for me. The result of the request is always empty.

<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>

Is that because of the Same Domain Policy? http://stackoverflow.com/questions/929677/how-exactly-is-the-same-domain-policy-enforced

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

function load_script(src) {
   var scrip = document.createElement('script');
   scrip.src = src;
   document.getElementsByTagName('head')[0].appendChild(scrip);
   return scrip;
}

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

load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse');
link|improve this question
feedback

1 Answer

up vote 1 down vote accepted

Yes, this is a XSS thing.

You can use JSONP (all API methods take a jsonp parameter for the callback name) to work around this.

Alternatively, you can use one of the Soapi.JS libraries, which handle this for you.

link|improve this answer
...or StackScript. – George Edison Dec 29 '10 at 16:39
feedback

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged