How can I link external json file in JSFiddle?

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

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


        
相关标签:
6条回答
  • 2021-02-06 08:10

    Step 1

    Go to http://myjson.com/

    I pasted in my json data and hit save I will then get a this link:

    https://api.myjson.com/bins/3ffb0

    enter image description here


    Step 2

    Now that I have that URL, I use it like this

        $http.get('https://api.myjson.com/bins/3ffb0').success(function(data) {
          $scope.countries = data;
        });
    

    My Result

    Work like a charm. No complain. :D


    0 讨论(0)
  • 2021-02-06 08:10

    You can't load a locally created .json file into Fiddler.

    Here I put a .json file that I found on the web, and you can see the data comes in from it (into the console as well).

    https://jsfiddle.net/v99e25r8/

    $http.get('https://json-generator.appspot.com/api/json/get/bVQoKFSGNu?indent=2')
        .success(function(data) {
            console.log(data);
            $scope.countries = data;
        });
    

    Fiddler aside, if this was within your project you just need to have it point to the correct directory.

    0 讨论(0)
  • 2021-02-06 08:17

    You can also put this json in a file on your server and load it using script tag.

    <script src="my.js"></script>
    

    And load this file before the script in which you are using it.

    my.js

    var myJson = [{.....}]; // My long json
    
    0 讨论(0)
  • 2021-02-06 08:19

    You can actually use a locally created json, in the jsfiddle documentation:

    new Request.JSON({
        url: '/echo/json/',
        data: {
            json: JSON.encode({
                text: 'some text',
                array: [1, 2, 'three'],
                object: {
                    par1: 'another text',
                    par2: [3, 2, 'one'],
                    par3: {}
                }
            }),
            delay: 3
        },
        onSuccess: function(response) {
            show_response(response, $('post'));
        }
    }).send();
    
    show_response = function(obj, result) {
        $H(obj).each(function(v, k) {
            new Element('li', {
                text: k + ': ' + v
            }).inject(result);
        });
        result.highlight();
    };
    

    Edit1

    It's not my code, it's their fiddle anyway ;) Here:

    http://jsfiddle.net/zalun/QsHw4/light/

    Edit2

    How do use your code with my code ?

    Alright, you can actually use their code instead, since your goal is to use jsfiddle. Here's one with part of your json:

    http://jsfiddle.net/QsHw4/6348/

    I turned the ul into a table like this:

    <table>
        <thead>
            <tr>
                <th>Country</th>
                <th>Population</th>
            </tr>
        </thead>
        <tbody id="post">
            <tr>
                <td>Lalaland</td>
                <td>0</td>
            </tr>
        </tbody>
    </table>
    

    Here's the fiddle with Mr. Polywhirl CSS table ;P

    http://jsfiddle.net/QsHw4/6351/

    0 讨论(0)
  • 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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    <div ng-app="countryApp">
      <div ng-controller="CountryCtrl">
        <table>
          <thead>
            <tr>
              <th>Country</th>
              <th>Population</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="country in countries">
              <td>{{country.name}}</td>
              <td>{{country.population}}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    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 = $('<tr>');
      $.each(fields, function(i, field) {
        row.append($('<td>').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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <table id="countryTable">
      <thead>
        <tr>
          <th>Country</th>
          <th>Population</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
    
    <script id="country-template" type="text/x-handlebars-template">
        <table>
          <thead>
            <tr>
              <th>Country</th>
              <th>Population</th>
            </tr>
          </thead>
          <tbody>
            {{#each .}}
            <tr>
              <td>{{name}}</td>
              <td>{{population}}</td>
            </tr>
            {{/each}}
          </tbody>
        </table>
    </script>

    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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
    
    <table>
      <thead>
        <tr>
          <th>Country</th>
          <th>Population</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
    
    <script type="text/html" id='table-data'>
      <% _.each(countries, function(country, key, list){ %>
        <tr>
          <td> <%= country.name %> </td>
          <td> <%= country.population %> </td>
        </tr>
        <% }) %>
    </script>

    Solution Using ExtJS (4.2)

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

    Ext.onReady(function() {
      var tpl = new Ext.XTemplate(
        '<table class="view_table">',
          '<thead>',
            '<tr>',
              '<th>Name</th>',
              '<th>Population</th>',
            '</tr>',
          '</thead>',
          '<tbody>',    
            '<tpl for=".">',    
              '<tr>',
                '<td>{name}</td>',
                '<td>{population}</td>',
              '</tr>',
            '</tpl>', 
          '</tbody>',
        '</table>'
      );
      
      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;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/resources/css/ext-all-neptune-debug.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/ext-all.min.js"></script>
    
    <div id="country-grid"></div>

    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(
        '<table class="view_table">',
          '<thead>',
            '<tr>',
              '<th>Name</th>',
              '<th>Population</th>',
            '</tr>',
          '</thead>',
          '<tbody>',    
            '<tpl for=".">',    
              '<tr>',
                '<td>{name}</td>',
                '<td>{population}</td>',
              '</tr>',
            '</tpl>', 
          '</tbody>',
        '</table>'
      );
      
      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;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/resources/css/ext-all-neptune-debug.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/ext-all.min.js"></script>
    
    <div id="countryApp"></div>


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

    0 讨论(0)
  • 2021-02-06 08:21

    If you put the JSON file in GitHub you may also Pass response directly from GitHub Repository.

    Your JSON file must be named demo.response.json and call it as below

    /gh/get/response.json/{github_tree}/

    For instance I have that JSON file here

    https://github.com/chetabahana/chetabahana.github.io/blob/master/_data/demo.response.json

    Then in JSFiddle you can get the data using Ajax as below:

    HTML

    <p>Result will appear below with 1 sec delay</p>
    <div id="demo"><p>This text will be replaced</p></div>
    

    JS (Choose one of Mootools Framework)

    window.addEvent('domready', function() {
        new Request.HTML({
            url: '/gh/get/response.json/chetabahana/chetabahana.github.io/tree/master/_data/',
            data: {'delay': 1},
            method: 'post',
            update: 'demo',
            onSuccess: function(response) {
                $('demo').highlight();
            }
        }).send();
    })
    

    Note: There is no JSONP functionality provided. One may achieve it using raw GitHub URL.

    0 讨论(0)
提交回复
热议问题