我正试图从服务器usin-php上的文本文件中读取值,并在js中使用它们。我使用的代码(在stackoverflow中找到)似乎是针对我需要的东西,但却出现了一个错误(Uncaught SyntaxError:Unexpected token<),似乎与php行有关。
LM.txt一行:ID、LAT、LNG
<script > (function(){
<?php echo "var fileContent = '" . file_get_contents("graphdata/LM.txt"). "'," ; ?>
alerts = fileContent.split("'n").map(function(lineItem){
// Assuming each line is csv: ID,LAT,LNG
// and that there are no commas in the values
var field = lineItem.split(",");
return {ID: field[0], LAT: field[1], LNG: fields[2]};
});
// now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}]; })(); </script>
我能做什么吗?
您的脚本文件是否具有.PHP扩展名?(否则它将不会被PHP解释器处理)
怎么样,你的代码似乎在内联注释中包含了一些标记-->//现在提醒。。。
<script >
(function() {
var fileContent = '<?php echo addslashes(file_get_contents("graphdata/LM.txt")) ?>',
alerts = fileContent.split("'n").map( function(lineItem){
// Assuming each line is csv: ID,LAT,LNG
// and that there are no commas in the values
var field = lineItem.split(",");
return { ID: field[0], LAT: field[1], LNG: fields[2] };
});
// now alerts looks like this: [{ID: ..., LAT: ..., LNG: ...}, {...}];
})();
</script>
<?PHP
$filecontent = str_replace("'n",''n',file_get_contents("graphdata/LM.txt"));
echo '
<script type="text/javascript">
var fileContent = "'.$filecontent.'";
// now the JS variable fileContent has the content of your file
var alerts = fileContent.split("'n").map(function(lineItem){
var field = lineItem.split(",");
return {ID: field[0], LAT: field[1], LNG: field[2]};
});
</script>
';
?>