简体   繁体   中英

jQuery - loading a text file with $.get() works in Internet Explorer, but not Google Chrome or Firefox?

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 \\n word \\n word \\n word \\n word".

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM