首页 > 解决方案 > 试图将 csv 数据获取到 javascript 数组并得到 404 错误

问题描述

我的站点中有一个使用大表(csv 格式)的验证。我试过以下代码:

let styleurl = document.getElementById("isthisthestore");
      styleurl = styleurl.getAttribute("data-stylesheeturl")
      console.log(styleurl);
      let data;
        $.ajax({
          type: "GET",
          url: styleurl + "/tambour.csv",
          dataType: "text",
          success: function(response)
          {
            data = $.csv.toArrays(response);
            console.log(data);
          }
        });

我从页面上的元素获取 url(我确信有更好的方法,但这不是问题......)

我收到一条错误消息:“GET https://correct-file-url/tambour.csv 404”

知道为什么吗?

标签: javascriptajaxurlget

解决方案


我为您创建了一个文件,让您看到一个简单的代码,但观察是检查完整的“url”,例如,当 var 将打印在控制台上时,复制此 url 并检查它,非常重要的是没有任何空格或双斜杠 (//),请参见示例:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>An Example for correct csv.toArrays</title>
</head>
<body>
<div id="isthisthestore" style="display: none;" data-id="https://yousiteweb.test/"> </div>



<script src="https://code.jquery.com/jquery-3.4.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/1.0.11/jquery.csv.min.js" integrity="sha512-Y8iWYJDo6HiTo5xtml1g4QqHtl/PO1w+dmUpQfQSOTqKNsMhExfyPN2ncNAe9JuJUSKzwK/b6oaNPop4MXzkwg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

  <script type="text/javascript">
var styleurl = $('#isthisthestore').attr('data-id'); //use jquery to get an url
var styleurl = styleurl+"tambour.csv"; //dont put slashes in the file name if your var url have a slash in the end of string, like data-id="https://yoursiteweb.test/"


console.log('the complete url is: '+styleurl); // check if your url+file is available
let data;
$.ajax({
          type: "GET",
          url: styleurl, //the var with the csv file
          dataType: "html", //type html for use jquery.csv
          success: function(response)
          {
             data = $.csv.toArrays(response);
            console.log(data);
          }
        });</script>

</body>
</html>

国王问候


推荐阅读