如何在不赋值数组变量的情况下读取数组数据

how to read array data without assigned to array variable

本文关键字:数组 情况下 读取 数据 变量 赋值      更新时间:2023-09-26

我有一个文件data.json .它有以下数据

[
"101 200",
"102 201",
"102 202",
"103 202"
]

如何使用 javascript 读取这些数据?请注意,它没有分配给任何变量,文件名以 .json 结尾,但里面的数据看起来不像 json 数据。

使用 ajax 方法获取文件(确保您的服务器对 JSON 文件使用正确的内容类型 HTTP 标头 ( application/json )。

当结果传递到成功处理程序时,它将显示为 JavaScript 数组。

工作演示 。(注意:仅适用于HTML5)

代码:

  function readSingleFile(evt) {
    //Retrieve the first (and only!) File from the FileList object
    var f = evt.target.files[0]; 
    if (f) {
      var r = new FileReader();
      r.onload = function(e) { 
          var contents = JSON.parse(e.target.result);
          console.log(contents);  
      }
      r.readAsText(f);
    } else { 
      alert("Failed to load file");
    }
  }
  $("#foo").change(readSingleFile);