Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

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');
share|improve this question
add comment

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.

share|improve this answer
    
...or StackScript‌​. –  Nathan Osman Dec 29 '10 at 16:39
    
You can also support the feature request to Add CORS headers to API output. (You can read about Cross-origin resource sharing on Wikipedia. –  hippietrail Jun 3 '12 at 13:33
add comment

You must log in to answer this question.

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