2013-09-26 7 views
10

ho questo codice:chiamate multiple di dati JSON/file in una richiesta getJSON

var graphicDataUrl = 'templating/graphic-data.json'; 
var webDataUrl = 'templating/web-data.json'; 
var templateHtml = 'templating/templating.html'; 
var viewG = $('#view-graphic'); 
var viewW = $('#view-web'); 

$.getJSON(dataUrls, function(data) { 
    $.get(templateHtml, function(template) { 
     template = Handlebars.compile(template); 
     var example = template({ works: data });   
     viewG.html(example); 
     viewW.html(example); 
    }); 
}); 

Qual è il modo migliore per la chiamata sia DataURL JSONs e utilizzare i dati in modo da visualizzarli in due diversi div (#viewW e #viewW) sulla mia pagina?

+0

'daataUrls' sembra non definito. – Utkanos

+0

Sì, è un segnaposto per far capire agli altri cosa voglio raggiungere –

risposta

27

Il modo migliore è quello di fare ciascuno individualmente, e per gestire le condizioni di errore:

$.getJSON(graphicDataUrl) 
    .then(function(data) { 
     // ...worked, put it in #view-graphic 
    }) 
    .fail(function() { 
     // ...didn't work, handle it 
    }); 
$.getJSON(webDataUrl, function(data) { 
    .then(function(data) { 
     // ...worked, put it in #view-web 
    }) 
    .fail(function() { 
     // ...didn't work, handle it 
    }); 

che permette le richieste di avvengono in parallelo, e aggiorna la pagina non appena possibile quando ogni richiesta completa.

Se si desidera eseguire le richieste in parallelo ma aspettare per aggiornare la pagina fino a che non sia completo, è possibile farlo con $.when:

var graphicData, webData; 
$.when(
    $.getJSON(graphicDataUrl, function(data) { 
     graphicData = data; 
    }), 
    $.getJSON(webDataUrl, function(data) { 
     webData = data; 
    }) 
).then(function() { 
    if (graphicData) { 
     // Worked, put graphicData in #view-graphic 
    } 
    else { 
     // Request for graphic data didn't work, handle it 
    } 
    if (webData) { 
     // Worked, put webData in #view-web 
    } 
    else { 
     // Request for web data didn't work, handle it 
    } 
}); 

... ma la pagina può sembrare meno reattivo dal momento che non si sta aggiornando quando la prima richiesta ritorna, ma solo quando entrambi lo fanno.

+0

Grazie mille! Questo è esattamente quello che stavo cercando. Ho Provalo ora :) –

+0

Così ora ho scritto questo: '$ GetJSON (graphicDataUrl, la funzione (i dati) { \t $ .get (templateHtml, la funzione (template) { \t \t template = Handlebars.compile (template) ; \t \t var = esempio template ({opere: dati}); \t \t \t \t viewG.html (esempio); \t});} ); $ GetJSON (webDataUrl, la funzione (i dati) { \t $ .get (templateHtml, la funzione (template) { \t \t template = Handlebars.compile (template); \t \t var esempio = modello ({funziona: i dati}); \t \t \t \t viewW.html (esempio); \t});} ); 'Ma ci sono un sacco ripetere codice! E posso anche farlo senza gestire l'errore? (p.s.non esiste un modo migliore per scrivere il codice in riproduzione?) –

+0

@GiorgiaSambrotta: Ovviamente c'è un modo migliore. :-) Puoi racchiuderlo in una funzione. Perché stai recuperando il template da 'templateHtml' invece di tenerlo e riusarlo? (Quella parte sembra completamente invariata tra i due.) –

10

Nel caso in cui sia utile a chiunque possa imbattersi in questo — e grazie agli anticipi Promessa in jQuery — T.J. La risposta di Crowder può ora essere migliorato in una succinta e generale funzione:

/** 
* Load multiple JSON files. 
* 
* Example usage: 
* 
* jQuery.getMultipleJSON('file1.json', 'file2.json') 
* .fail(function(jqxhr, textStatus, error){}) 
* .done(function(file1, file2){}) 
* ; 
*/ 
jQuery.getMultipleJSON = function(){ 
    return jQuery.when.apply(jQuery, jQuery.map(arguments, function(jsonfile){ 
    return jQuery.getJSON(jsonfile); 
    })).then(function(){ 
    var def = jQuery.Deferred(); 
    return def.resolve.apply(def, jQuery.map(arguments, function(response){ 
     return response[0]; 
    })); 
    }); 
}; 

Tuttavia il punto di non dare alcun feedback all'utente — in attesa per il pieno carico — è un buon compromesso. Quindi per coloro che preferiscono dare un feedback reattivo, ecco una versione leggermente più complicata che supporta il progresso.

/** 
* Load multiple json files, with progress. 
* 
* Example usage: 
* 
* jQuery.getMultipleJSON('file1.json', 'file2.json') 
* .progress(function(percent, count, total){}) 
* .fail(function(jqxhr, textStatus, error){}) 
* .done(function(file1, file2){}) 
* ; 
*/ 
jQuery.getMultipleJSON = function(){ 
    var 
    num = 0, 
    def = jQuery.Deferred(), 
    map = jQuery.map(arguments, function(jsonfile){ 
     return jQuery.getJSON(jsonfile).then(function(){ 
     def.notify(1/map.length * ++num, num, map.length); 
     return arguments; 
     }); 
    }) 
    ; 
    jQuery.when.apply(jQuery, map) 
    .fail(function(){ def.rejectWith(def, arguments); }) 
    .done(function(){ 
     def.resolveWith(def, jQuery.map(arguments, function(response){ 
     return response[0]; 
     })); 
    }) 
    ; 
    return def; 
}; 
Problemi correlati