简体   繁体   中英

Assigning the content of a txt file on server to a javascript variable

Here is my problem (which is rather simple).

How can I assign the content of a file on my server to a javascript variable ?

Here is what I tried so far:

var count= <?php echo file_get_contents("compteur.txt");?>

But it doesn't funciton. BTW: I spent two hours on google already.

如果文件的内容不是数字值,则必须使用'" ,如下所示

var count= '<?php echo file_get_contents("compteur.txt");?>';

Simply outputting the file's contents in between single quotes will present a lot of pitfalls. If you're using PHP 5.2 or higher, you can use json_encode , which should be a lot more foolproof:

var count = <?php echo json_encode(file_get_contents("compteur.txt")); ?>

json_encode will take care of surrounding the value in quotes, so you do not need to put quotes before and after the PHP snippet.

On versions of PHP before 5.2, you can use this less robust technique for escaping the value:

function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}

Source

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