PDA

View Full Version : Text File as Source for JavaScript variable?



johnnyi
03-22-2006, 06:00 PM
Howdy,

Without having to use an ActiveX control, is there a way for a JavaScript function to set a variable value equal to the contents of a specified .txt file? For example, set 'var a' to a particular row in a .txt file (or, if need be, the entire .txt file contents). The only caveat being that the page needs to remain as an .htm or .html (i.e. - no .asp).

Please let me know if you need any additional detail...

- I

ddadmin
03-23-2006, 05:55 PM
Well in general it's possible to "serialize" the contents of a text file (or HTML file) and store it as a JavaScript variable. The tricky part has always been about the syntax, as any special characters or line breaks in the content will throw a JavaScript error as it gets interpreted literally (instead of as part of the variable's content).

There are many ways to go about "serializing" a file content to be stored inside a JavaScript variable. Coming from PHP, the simpliest way is just to encode the content, then decode it back in JavaScript. For example:



//PHP code on server side
echo "var JSvar=\"rawurlencode($thecontent)\"";


This causes the server to ouput a JavaScript variable called "JSvar" containing whatever arbitrary content you wanted to serve via JS. Then, on the client side, you'll want to decode the content before actually showing it:


//JavaScript code on client side
alert(unescape(JSvar))

Twey
03-23-2006, 06:04 PM
//PHP code on server side
echo "var JSvar=\"rawurlencode($thecontent)\""; The output of this will be:
var JSvar="rawurlencode(Arbitrary content)";I don't know if that's what you meant to say.

Also, the OP said server-side stuff was out-of-bounds (well, actually, s/he said ASP was, but I presume that's what s/he meant).

ddadmin
03-23-2006, 08:46 PM
Hmm maybe I should clarify. I meant something like:


<script type="text/javascript">
<?
//PHP code on server side
echo "var JSvar=\"rawurlencode($thecontent)\"";
?>
</script>

That way, the JavaScript variable "JSvar" now contains the desired contents, but encoded to easily neutralize any special characters, line breaks etc in the content.

Then, on the client side, when you actually want to make use of the content within "JSvar", you need to unescape it, to undo the escaping done by PHP's rawurlencode().

Twey
03-23-2006, 09:11 PM
The point I was making is that since the rawurlencode() call is within the quotes, it is never actually called, and output as a string, giving an output in your last example (if $thecontent was "Arbitrary content") of:
<script type="text/javascript">
<?
var JSvar="rawurlencode(Arbitrary content)";
?>
</script>... which will be unparsable by Javascript. I think you may mean to say:
echo("var JSvar=\"" . rawurlencode($thecontent) . "\"");