kentcdodds kentcdodds - 1 year ago 88
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 = '';

request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
var gistFileContent = request.responseText;
};'GET', gistRawFileUrl, true);

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

XMLHttpRequest cannot load Origin 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!

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 Source

Check out this answer:

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:

  url: ''+gistid,
  type: 'GET',
  dataType: 'jsonp'
}).success( function(gistdata) {
    var content =[filename].content;
  }).error( function(e) {
  // ajax error


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