简体   繁体   中英

cannot find json file stored locally

for some reason, the code can't open the local file. currently my file is located at C:/file_folder/file_name

here's the code:

function loadJSON(callback) 
{   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', './file_folder/file_name', true);
  xobj.onreadystatechange = function () {
  if (xobj.readyState == 4 && xobj.status == "200") {
    callback(JSON.parse(xobj.responseText));
    }
  };
  xobj.send(null);  
}

is my url wrong?

You stated that your script is ran from C:/file_folder/

The file you want to read is at C:/file_folder/file_name

The relative path from the script to the file would be ./file_name not ./file_folder/file_name

./file_folder/file_name is actually looking in C:/file_folder/file_folder/file_name in this case

Granted this would only work if this was a script ran on your computer or it was referencing a file from the server the webpage is hosted from. Otherwise a webpage can not read your local file-system.

Javascript in the browser cannot read from your filesystem.

You have to set up a server to send the file from an endpoint.

Here's the fs module from node for reading a file: https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback

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