Recuperare JSON con StackOverflow API
-
13-10-2019 - |
Domanda
voglio recuperare le informazioni dal mio profilo Stack Overflow come JSON utilizzando l'API.
Quindi io uso questo link http: /api.stackoverflow.com/1.0/ utenti / 401.025 / .
Ma quando faccio la richiesta ho un file contenente i dati JSON. Come faccio a trattare con il file utilizzando Ajax?
Ecco il mio codice ( 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>
L'avviso viene mai licenziato e req.responseText
sembra essere vuoto. Tutte le idee?
Soluzione
Nota: Non è possibile utilizzare Ajax per accedere a un altro dominio. (Questo è chiamato il politica dello stesso dominio .)
Tuttavia, l'API StackOverflow supporta callback JSONP, ecco una soluzione:
Carica nello script tramite un tag <script>
.
Creare una funzione che fa proprio questo:
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
}
Impostare la funzione di callback:
function soResponse(obj) {
alert(obj.users[0].reputation);
}
Carica esso!
load_script('http://api.stackoverflow.com/1.0/users/401025/?jsonp=soResponse');