1

I'm loading a (fairly large) text file into an array using jQuery. When I open the page in Internet Explorer, the array has loaded in perfectly - I can load any element in the array onto the page. When I open the page in Google Chrome / Firefox, the array hasn't loaded at all. The rest of the page is functional, but when I try to load in an element, it just says undefined where the array would have been.

I don't think the file size is the problem, because when opened in Internet Explorer, the array loads pretty fast - nothing seems unresponsive. The file is formatted as "word\nword\nword\nword\nword".

Here's the code I use to load the text file into an array:

var wordList = new Array();
    $.get('words.txt', function(data){
         wordList = data.split('\n');
    });

Later, I used this to test whether the array had loaded:

$('#words').append($('#input').val() + ' ' + wordList[word.length]);

For context, #words is a <p> and #input is a text input. I take the word given in the input and get its length, then I use that as an index for the word list I loaded in earlier. In Internet Explorer, it'll load whatever should be at that index, but in any other browser, it just loads undefined.

I did some research and it looks like there's a problem with the same-origin policy. At least, that's the error I'm getting from the console in Chrome:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I looked around for some solutions to this, but they all seem to involve finding a way to make a cross-domain request - I don't think that's what I should be doing, though, because this is all on my own PC's filesystem. What's up here?

Arnav
  • 115
  • 2
  • 11
  • 1
    "*`Origin 'null' is therefore not allowed access.`*" You should host your pages and scripts on an `http://` server. `file://` doesn't normally allow Ajax. – Jonathan Lonowski Mar 22 '14 at 03:51
  • So I can get a web host and just put the files on there, and it should work? – Arnav Mar 22 '14 at 03:53
  • That should resolve the `No 'Access-Control-Allow-Origin'` errors, at least. And, a web host is one option, but you can also run an HTTP static server yourself -- [some with just a command or two](https://gist.github.com/willurd/5720255). – Jonathan Lonowski Mar 22 '14 at 04:01
  • I love you. HTTP server worked, and the python one-liner was insanely easy compared to stuff I was finding with google. Thank you! – Arnav Mar 22 '14 at 04:06

1 Answers1

2

You are unable to open file:// links in Chrome/FF due to their security model. I believe there are some extensions you can download which make it possible though. Accessing the file through http will solve the problem though.

Another answer to the same problem

Community
  • 1
  • 1
RLS
  • 311
  • 1
  • 13