How can I link external json file in JSFiddle?

后端 未结 6 1534
北荒
北荒 2021-02-06 07:33
  • I have a very long .json file country.json.

[
  {
    "name": "WORLD",
    "population": 6916183000         


        
6条回答
  •  佛祖请我去吃肉
    2021-02-06 08:20

    JSFiddle does not allow you to upload JSON files to make AJAX requests. You will need to have some other way to host the files so that you can call them. Your best bet is to upload them on an external server, preferably yours.

    JSON-P to the Rescue!

    Since the files will be hosted outside of the jsfiddle.net domain, you will either need to make a CORS request or, a simpler solution, a JSON-P request, which allows you to make cross-domain AJAX requests to retrieve JSON data.

    What If I Cannot Host the File?

    Accessing a JSON file on your own network should not be a problem. Since this is a JSFiddle question, you can only do what is suggested above. Someone suggested the JSFiddle mock AJAX request, but this still requires you to paste your JSON directly into the editor. If you cannot host the JSON externally, the least you can do is wrap it in a function at the end of your script. This will keep it out of sight so you don't have to scroll through it.

    Here is a JSFiddle demonstrating their mock AJAX feature, using the JSON you provided: http://jsfiddle.net/MrPolywhirl/QsHw4/6352/

    NOTE: You cannot call a file over HTTP in JSFiddle, if you are using their HTTPS connection. If you request cannot be called using HTTPS, you will need to find another way to access the file.


    Solutions Using Template Languages

    Here are tow example, one in Angular and one in jQuery, which produce the same ouptup using JSON-P.

    Solution Using Angular

    Using an externally hosted JSON file:

    http://beta.json-generator.com/api/json/get/CK4M2Hk?indent=2&callback=JSON_CALLBACK

    You can make a JSONP request in Angular JS like so:

    var jsonDataUrl = 'http://beta.json-generator.com/api/json/get/CK4M2Hk?indent=2&callback=JSON_CALLBACK';
    
    var countryApp = angular.module('countryApp', []);
    
    countryApp.controller('CountryCtrl', function($scope, $http) {
      $http.jsonp(jsonDataUrl)
        .success(function(data) {
          console.log(data);
          $scope.countries = data;
        });
    });
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    Country Population
    {{country.name}} {{country.population}}

    Solution Using jQuery

    If you are unfamiliar with Angular, here is a jQuery implementation.

    var jsonDataUrl = 'http://beta.json-generator.com/api/json/get/CK4M2Hk?indent=2&callback=JSON_CALLBACK';
    
    $(function() {
      $.ajax({
        type: 'GET',
        url: jsonDataUrl,
        async: false,
        jsonpCallback: 'JSON_CALLBACK',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data) {
          addRows($('#countryTable'), data, ['name','population']);
        },
        error: function(e) {
          console.log(e.message);
        }
      });
    });
    
    function addRows(table, data, fields) {
      var tbody = table.find('tbody');
      $.each(data, function(i, item) {
        tbody.append(addRow(item, fields));
      });
      return tbody;
    }
    
    function addRow(item, fields) {
      var row = $('');
      $.each(fields, function(i, field) {
        row.append($('').html(item[field]));
      });
      return row;
    }
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    Country Population

    Solution Using HandlebarsJS

    Similar to the jQuery example except we use a template instead of inserting DOM elements.

    var jsonDataUrl = 'http://beta.json-generator.com/api/json/get/CK4M2Hk';
    
    $(function() {
      var theTemplateScript = $("#country-template").html();   // Grab the template script
      var theTemplate = Handlebars.compile(theTemplateScript); // Compile the template
      
      $.ajax({
        type: 'GET',
        url: jsonDataUrl,
        async: false,
        jsonpCallback: 'JSON_CALLBACK',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data) {
          var theCompiledHtml = theTemplate(data);  // Pass our data to the template
    
          $('body').append(theCompiledHtml); // Add the compiled html to the page
        },
        error: function(e) {
          console.log(e.message);
        }
      });
    });
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    

    Solution Using UnderscoreJS

    An alternative template to the HandlebarsJS example.

    var jsonDataUrl = 'http://beta.json-generator.com/api/json/get/CK4M2Hk';
    var countries = [];
    
    $(function() {
      var tableTemplate = _.template($("#table-data").html());
      
      $.ajax({
        type: 'GET',
        url: jsonDataUrl,
        async: false,
        jsonpCallback: 'JSON_CALLBACK',
        contentType: "application/json",
        dataType: 'jsonp',
        success: function(data) {
          $("table>tbody").html(tableTemplate({
            countries: data
          }));
        },
        error: function(e) {
          console.log(e.message);
        }
      });
    });
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    
    Country Population

    Solution Using ExtJS (4.2)

    I went ahead and also created a solution using Ext JS.

    Ext.onReady(function() {
      var tpl = new Ext.XTemplate(
        '',
          '',
            '',
              '',
              '',
            '',
          '',
          '',    
            '',    
              '',
                '',
                '',
              '',
            '', 
          '',
        '
    NamePopulation
    {name}{population}
    ' ); Ext.data.JsonP.request({ url: 'http://beta.json-generator.com/api/json/get/CK4M2Hk', params : { callback : 'Ext.data.JsonP.callback1' }, method: 'GET', callback: function(success, response, data) { Ext.get(Ext.dom.Query.select('#country-grid')).setHTML(tpl.apply(response)); } }); });
    body {
      background: #FFF !important;
    }
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    

    Solution Using ExtJS (4.2) Using a DataView

    This is a more advanced and complete ExtJS template example. A DataView, Model, and Store are used to store and display the data in the template.

    var jsonDataUrl = 'http://beta.json-generator.com/api/json/get/CK4M2Hk?indent=2&callback=Ext.data.JsonP.callback1';
    
    Ext.onReady(function() {
      Ext.define('app.model.Country', {
        extend: 'Ext.data.Model',
        fields: [{
          name: 'name',
          type: 'string'
        }, {
          name: 'population',
          type: 'int'
        }]
      });
    
      Ext.create('Ext.data.Store', {
        storeId: 'countryStore',
        model: 'app.model.Country',
        autoLoad: true,
        proxy: {
          type: 'jsonp',
          url: jsonDataUrl,
          reader: {
            type: 'json'
          }
        }
      });
    
      var tpl = new Ext.XTemplate(
        '',
          '',
            '',
              '',
              '',
            '',
          '',
          '',    
            '',    
              '',
                '',
                '',
              '',
            '', 
          '',
        '
    NamePopulation
    {name}{population}
    ' ); Ext.create('Ext.DataView', { width : 500, height : 200, renderTo : 'countryApp', store : Ext.getStore('countryStore'), tpl : tpl }); });
    body {
      background: #FFF !important;
    }
    table {
      background: #DDD;
    }
    thead tr {
      background: #9D9;
    }
    tbody tr:nth-child(2n) {
      background: #CFC;
    }
    tbody tr:nth-child(2n+1) {
      background: #EFE;
    }
    th, td {
      width: 100px;
      padding: 0.2em;
      text-align: center;
    }
    
    
    
    


    The JSON data was generated using this generator function: http://beta.json-generator.com/CK4M2Hk

提交回复
热议问题