2016-02-09 11 views
5

Ho bisogno di costruire un progetto per entrare in un bootcamp JS a cui mi sto candidando. Mi dicono che posso usare solo JS vanilla, in particolare che i framework e Jquery non sono consentiti. Fino a questo punto, quando ho voluto recuperare un file JSON da un api direi

$.getJSON(url, functionToPassJsonFileTo) 

per le chiamate JSON e

$.getJSON(url + "&callback?", functionToPassJsonPFileTo) 

per JSONP chiama. Ho appena iniziato a programmare questo mese, quindi tieni presente che non conosco la differenza tra JSON o JSONP o il modo in cui si riferiscono a questa cosa chiamata ajax. Per favore, spiega come otterrei ciò che le 2 linee sopra raggiungono in Vanilla Javascript. Grazie.

Quindi, per chiarire,

function jsonp(uri){ 
    return new Promise(function(resolve, reject){ 
     var id = '_' + Math.round(10000 * Math.random()) 
     var callbackName = 'jsonp_callback_' + id 
     window[callbackName] = function(data){ 
      delete window[callbackName] 
      var ele = document.getElementById(id) 
      ele.parentNode.removeChild(ele) 
      resolve(data) 
     } 

     var src = uri + '&callback=' + callbackName 
     var script = document.createElement('script') 
     script.src = src 
     script.id = id 
     script.addEventListener('error', reject) 
     (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script) 
    }) 
} 

sarebbe l'equivalente JSONP?

risposta

16

ecco la versione Vanilla JS per $.getJSON:

var request = new XMLHttpRequest(); 
request.open('GET', '/my/url', true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    // Success! 
    var data = JSON.parse(request.responseText); 
    } else { 
    // We reached our target server, but it returned an error 

    } 
}; 

request.onerror = function() { 
    // There was a connection error of some sort 
}; 

request.send(); 

Rif: http://youmightnotneedjquery.com/

Per JSONP ha così già la risposta here

Con $.getJSON è possibile caricare i dati JSON-encoded dal server utilizzando una richiesta HTTP GET.

+0

Questo è l'equivalente di '$ .getJSON()', se non è chiaro. Ottenere JSONP è significativamente diverso. – Pointy

+2

Questo link è una risorsa molto utile, ecco un confronto riga per riga: http://youmightnotneedjquery.com/#json –

+0

Ma non jquery 1.x gestione IE8 ??? –

0

Apprezzo l'equivalente di vaniglia di $ .getJSON sopra ma vengo esattamente allo stesso punto. In realtà stavo cercando di sbarazzarmi di jquery che non padroneggio in alcun modo. Ciò di cui sono finalmente alle prese con ENTRAMBI i casi è la natura asincrona della richiesta JSON.

Quello che sto cercando di raggiungere è quello di estrarre una variabile dalla chiamata asincrona

function shorten(url){ 

var request = new XMLHttpRequest(); 
bitly="http://api.bitly.com/v3/shorten?&apiKey=mykey&login=mylogin&longURL="; 
request.open('GET', bitly+url, true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    var data = JSON.parse(request.responseText).data.url; 
    alert ("1:"+data); //alerts fine from within 
    // return data is helpless 
    } 
}; 

request.onerror = function() { 
    // There was a connection error of some sort 
    return url; 
}; 

request.send(); 

} 

ora che la funzione è definita & funziona a meraviglia

shorten("anyvalidURL"); // alerts fine from within "1: [bit.ly url]" 

ma Come si assegna il valore dei dati (dalla chiamata asincrona) per poterlo usare nel mio javascript dopo che la funzione è stata chiamata

come ad esempio

document.write("My tiny is : "+data); 
+0

> ma come assegno il valore dei dati (dalla chiamata asincrona) - Dovrai passare una funzione di callback .. qualcosa come 'function shorten (url, onSuccess)' e quindi chiamare l'onSuccess con l'oggetto result ... cioè ' data' – Milli

2

ES6 ha Fetch API che fornisce un fetch() metodo globale che fornisce un modo semplice logica per andare a prendere le risorse in modo asincrono attraverso la rete.

È più semplice di XMLHttpRequest.

fetch(url) // Call the fetch function passing the url of the API as a parameter 
.then(function() { 
    // Your code for handling the data you get from the API 
}) 
.catch(function() { 
    // This is where you run code if the server returns any errors 
}); 
Problemi correlati