Pull in JSON data

后端 未结 3 1464
南笙
南笙 2021-01-24 07:22

I am trying to get an event calendar working from json data. I just want to highlight dates, and have a div update below the calendar with the event details when the user clicks

相关标签:
3条回答
  • 2021-01-24 07:56

    In order to get JSON data from another domain, you have to use JSONP with a callback function. The Github API supports this (example), and jQuery handles making the callback automatically with dataType: 'jsonp'.

    This is how I get JSON data from a Github gist with jQuery:

    $.ajax({
      url: 'https://api.github.com/gists/'+gistid,
      type: 'GET',
      dataType: 'jsonp'
    }).success( function(gistdata) {
      // This can be less complicated if you know the gist file name
      var objects = [];
      for (file in gistdata.data.files) {
        if (gistdata.data.files.hasOwnProperty(file)) {
          var o = JSON.parse(gistdata.data.files[file].content);
          if (o) {
            objects.push(o);
          }
        }
      }
      if (objects.length > 0) {
        // DoSomethingWith(objects[0])
      }
    }).error( function(e) {
      // ajax error
    });
    

    (jsFiddle)

    0 讨论(0)
  • 2021-01-24 07:56

    Quite a lot of code to dig through, but aren't you making an asynchronous call and then trying to return a value from an anonymous function? Trying to use events just after initiating getJSON but probably quite a bit before the data is actually fetched?

    0 讨论(0)
  • 2021-01-24 07:58

    This error is coming because the request

     $.getJSON("https://raw.github.com/gist/1676157/15ce81851e57dfcecb985039e970a749585959de/my.json") 
    

    is not in same domain.So console.log() shows this error

      Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
    

    Running $.getJSON('Same domain request') will cause no error.

    See the fiddle and see console error message. http://jsfiddle.net/PGmFv/10/

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