How do I load a text file into a javascript variable as a string?

Discussion in 'JavaScript' started by komirad, Sep 5, 2007.

  1. #1
    As the title says...
    And also:
    Can the text file be any extension other than .txt

    I have done this using flash, need to know if it can be done using JS
     
    komirad, Sep 5, 2007 IP
  2. mjamesb

    mjamesb Member

    Messages:
    88
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    48
    #2
    The only way I know that it can be done is to use ajax to load the file which will return it as a string variable. The file has to be on a resolvable path on your web site. I have seen it done with .txt, .html, .json etc.... sorry don't have any sample code handy but that is where I would start looking
     
    mjamesb, Sep 6, 2007 IP
  3. loibeignacio

    loibeignacio Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    hi,

    you mean load the contents of a text file ( or any file ) ?

    If yes, you can try PHP's file_get_contents:

    <?php
    $content = file_get_contents('some_text_file.txt');
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    <script type="text/javascript">
    	var some_var = '<?php echo $content?>';
    	window.onload = function() {
    		document.getElementById('content').innerHTML = some_var;
    	}
    </script>
    </head>
    <body>
    <div id="content"></div>
    </body>
    </html>
    PHP:
    * you should sanitize the $content first or add some js functions to clean the output

    -Loibe
     
    loibeignacio, Sep 8, 2007 IP
  4. MMJ

    MMJ Guest

    Messages:
    460
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yeah, ajax would work fine.
     
    MMJ, Sep 9, 2007 IP