Reputation: 2304
So I have a text file, let's call it plaintext.txt
, and it's stored locally and I'm trying to read it in javascript, from the same folder that my js is running from.
In my html, I have
<script id="plaintext" src="plaintext.txt" type="text/plain"></script>
In my js I have
var text = document.getElementById('plaintext').textContent;
When running it I get the error in the console (warning?)
Resource interpreted as Script but transferred with MIME type text/plain: "file:///path/to/file/plaintext.txt".
And I just get a blank string
.
I just want to get the text from this file!!!! What am I doing wrong? Am I incorrect to think that this can be done this way? Is there a way to do this without using any external libraries like jQuery? I'm pretty new to javascript and I'm kind of astounded how hard it is just to read a local file! (though I do understand the security risks)
Upvotes: 1
Views: 2181
Reputation: 53
Get rid of:
<script id="plaintext" src="plaintext.txt" type="text/plain"></script>
Script tags are meant for loading scripts, not plain text files. Maybe Reading a local text file in JavaScript could be of some use to you. Otherwise go server side (which is much more convenient in your case), especially if you want to handle large amounts of data. So instead of storing everything in a file, you could store it in a database instead. If you're interested, go install Netbeans and get an MySQL database. Tutorialpoint is a great resource for learning java server page , sql, etc. Hope this helps :).
Upvotes: 1
Reputation: 2304
I ended up just doing this with jQuery, using the example that can be found at jquery - Read a text file?
Upvotes: 0