Call multiple JSON data/files in one getJson request

前端 未结 3 1967
执笔经年
执笔经年 2020-12-08 09:18

I have this code:

var graphicDataUrl = \'graphic-data.json\';
var webDataUrl = \'web-data.json\';
var templateHtml = \'templating.html\';
var viewG = $(\'#vi         


        
3条回答
  •  旧巷少年郎
    2020-12-08 09:22

    The best way is to do each one individually, and to handle error conditions:

    $.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
        });
    

    That allows the requests to happen in parallel, and updates the page as soon as possible when each request completes.

    If you want to run the requests in parallel but wait to update the page until they both complete, you can do that with $.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
        }
    });
    

    ...but the page may seem less responsive since you're not updating when the first request comes back, but only when both do.

提交回复
热议问题