-2

I am trying to grab json data from reddit using vanilla javascript and I found something perplexing. I found this question here grabbing Reddit data via javascript where there is a very solid solution making use of jQuery.

Here is the jsfiddle they shared. http://jsfiddle.net/DHKtW/353/ we can see the $.getJSON is working.

So I implement my own getJSON function like this:

  var getJSON = function(url, callback) {
      var xhr = new XMLHttpRequest();
      xhr.open('GET', url, true);
      xhr.responseType = 'json';
      xhr.onload = function() {
        var status = xhr.status;
        if (status === 200) {
          callback(null, xhr.response);
        } else {
          callback(status, xhr.response);
        }
      };
      xhr.send();
  };
  // let url = 'http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback';
  // let url = 'https://www.reddit.com/r/CryptoCurrency/.json?jsonp=?';
  let url = 'http://www.reddit.com/r/pics/.json?jsonp=?';
  getJSON(url , function(err, data) {
    if (err !== null) {
      console.log('Something went wrong: ' + err);
    } else {
      // console.log('Your query count: ' + data.query.count);
      console.log('Your query count: \n');
      console.log(data.query);
    }
  });

You can see in the code I have a couple of test urls that I tried. the yahooapis.com worked fine, reddit didn't. I am thinking this has something to do with jsonp. Here is a jsfiddle I set up to demonstrate that my code doesn't work. https://jsfiddle.net/9ky480c8/ here it is throwing an error that the request must be sent over https, which wasn't the case in the other jsfiddle.

Anyone know how to handle this with pure javascript?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Thomas Valadez
  • 1,697
  • 2
  • 22
  • 27

1 Answers1

0

It looks like you can ignore the JSONP issue by just omitting that query parameter. For that Reddit API, https://www.reddit.com/r/CryptoCurrency/.json seems to work just fine on its own and returns pure, normal JSON.

If you want to use JSONP, check out JavaScript XMLHttpRequest using JsonP for a method of doing it with pure Javascript and XHR.

Steven Goodman
  • 576
  • 3
  • 15