简体   繁体   English

将数据从.txt文件发送到JavaScript数组

[英]Send data from .txt file to JavaScript array

I have following simple.txt file: 我有以下simple.txt文件:

new google.maps.LatLng(37.782551, -122.445368)
new google.maps.LatLng(37.754665, -122.403242)
new google.maps.LatLng(37.753837, -122.403172)
new google.maps.LatLng(37.752986, -122.403112)
new google.maps.LatLng(37.751266, -122.403355)

following JavaScript code: 以下JavaScript代码:

function initialize() {
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(37.774546, -122.433523),
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  var pointArray = new google.maps.MVCArray(taxiData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });

  heatmap.setMap(map);
}

and following array: 和以下数组:

    var taxiData = [ 
    new google.maps.LatLng(37.782551, -122.445368)
    new google.maps.LatLng(37.754665, -122.403242)
    new google.maps.LatLng(37.753837, -122.403172)
    new google.maps.LatLng(37.752986, -122.403112)
    new google.maps.LatLng(37.751266, -122.403355)
];

I would like to send my data from simple.txt to taxiData array in JavaScript. 我想将数据从simple.txt发送到JavaScript中的taxiData数组。 I have tried something like this (without success): 我已经尝试过这样的事情(没有成功):

var taxiData = [
    <?php
    echo file_get_contents("simple.txt");
    ?>
];

Can you help me? 你能帮助我吗?

You need to separate the array elements with commas. 您需要使用逗号分隔数组元素。 You can do that easily enough in PHP: 您可以在PHP中足够容易地做到这一点:

<?php echo implode(',', explode('\n', file_get_contents("simple.txt"))); ?>

That simply breaks the file into an array of newline-delimited elements, then joins them back together using commas, creating a valid format that can be passed into the JavaScript code without issue. 只需将文件分成换行符分隔的元素数组,然后使用逗号将它们重新连接在一起,即可创建有效的格式,该格式可以毫无问题地传递到JavaScript代码中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM