Reputation: 70466
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?
Upvotes: 8
Views: 3204
Reputation: 199
For any future readers:
I wanted to get my Reputation without using oAuth and a whole library to do so. Thanks to Sebastien Horin's answer I easily could using the following:
function get_reputation() {
const xhttp = new XMLHttpRequest();
const url = 'https://api.stackexchange.com/2.3/users/USER_ID?&site=stackoverflow';
xhttp.open( "GET", url );
xhttp.send();
xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
var json = JSON.parse(xhttp.responseText);
console.debug( json );
}
}
}
get_reputation();
Note: this uses API v2.3.
Upvotes: 1
Reputation: 11069
there is a new API ( replace USER_ID )
https://api.stackexchange.com/2.2/users/[USER_ID]?&site=stackoverflow
Upvotes: 0
Reputation: 163288
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');
Upvotes: 10