2

I tried to retrieve information of my user profile on Stack Overflow 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?

However, the Stack Overflow 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');
1

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.

|improve this answer|||||

You must log in to answer this question.

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