Reputation: 65
I am new to Javascript and HTML5.
What is the best way to store text data to be read in JS.
I want to load all the characters of a file into an array, the file is similar to a map file and is stored amongst my resource file.
In Java I would create a text file and read each byte into an array, what is the equivalency of doing that in JS? Does JS have a better method of doing this?
Upvotes: 2
Views: 2590
Reputation: 123
Best way - create .js file with JSON encoded data. Almost all languages have functions for this, json_encode in PHP for example.
You can create a file like:
window.data = {something: true, fromfile: ['f','d','s']};
and include it as javascript file on html page:
<script src="data.js"></script>
So you'll have that array in window.data.
Or create a file:
{something: true, fromfile: ['f','d','s']}
And load it with jQuery's AJAX:
$.post('fileURL',{}, function(data) { console.log(data); }, 'json');
and get it at any moment you need it. You can also generate such data at any time with server-side scripts to get actual data, just change fileURL.js to server-side script's URL.
You can also change last parameter (json) to 'text' and get file content as string. But I'd not trust it for binary files, better to convert it on server side to JSON.
Upvotes: 1