kentcdodds kentcdodds - 6 months ago 31
Javascript Question

Get Raw Gist File

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.

jnv jnv
Answer

Check out this answer: http://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.