1

What I want is simple. Is there any way (including a work around) to make this work?

function loadXMLDoc() {
  var request = new XMLHttpRequest();
  var gistRawFileUrl = 'https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md';

  request.onreadystatechange = function() {
    if (request.readyState === 4 && request.status === 200) {
      var gistFileContent = request.responseText;
      doSomethingCool(gistFileContent);
    }
  };

  request.open('GET', gistRawFileUrl, true);
  request.send();
}

Right now, if I execute this in the console here I'm getting:

XMLHttpRequest cannot load https://gist.github.com/kentcdodds/5822336/raw/6ef128c8c8d6fe416782d969efa95d36e0acf374/KentsBlog.md. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.

This makes sense, and I know I'm not going to get GitHub to open up their access control, but if there's a work around to this or if I'm doing something wrong that would be great.

I realize that you can get the content of the file, by hitting the JSONP endpoint, but that doesn't give you the newline characters, so what was once this:

Hello World!
You
Rock!

Is now this:

Hello World!YouRock!

Thanks in advance.

Edit The problem with the newlines is something I need to fix on my end, not a Gist thing.

3
  • Possibly this will work? github.com/kares/script.js
    – kentcdodds
    Commented Aug 11, 2013 at 1:13
  • I voted to close this because it's not useful for anyone in the future. The problem was unrelated to reading raw gists from github.
    – kentcdodds
    Commented Sep 30, 2013 at 14:58
  • In a comment, OP said that he wanted this closed.
    – Mike
    Commented Oct 1, 2013 at 3:35

1 Answer 1

9

Check out this answer: https://stackoverflow.com/a/10454873/240963

API endpoint will give you content of each file within the Gist, including the formatting. The only downside is that you need to transfer extra data even if you already know the URL for the raw file.

We can simplify the code from the original answer, since you don't want to parse JSON and you probably know the filename:

$.ajax({
  url: 'https://api.github.com/gists/'+gistid,
  type: 'GET',
  dataType: 'jsonp'
}).success( function(gistdata) {
    var content = gistdata.data.files[filename].content;
    DoSomethingWith(content)
  }).error( function(e) {
  // ajax error
});

JSFiddle

Using JSONP with raw XHR is a bit more complicated, but you could use something lighter than jQuery.

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.