How to upload a local file using jQuery? (with file: //)

Is there a way to load data from a data file (e.g. JSON.js file) using jQuery?

eg:

$.get("file:///C:/objectData.js", function() { alert('Load was performed.'); }); 

At the moment, instead of a simple HTTP GET, jQuery seems to be trying to execute an OPTIONS request on it, which does not work in the file: // URI. I just want to download the data so that the site can be used in a standalone environment (without a web server installed).

+7
source share
2 answers

GET requires an HTTP connection, so without a local web server it will not work. Although you can open and read the file using HTML5, you cannot load the JavaScript resource this way.

If the page loads locally, you usually load JS with a script tag.

 <script type='text/javascript' src='/objectData.js'></script> 

There can only be one way in this answer: Can I load JavaScript into the local version instead of the server version?

or this (both require creating a local pseudo-server):

+5
source

Hope this is possible. I tried. HTML code and text files are in the same folder.

Here is the jQuery part.

 $(document).ready(function() { $("select").change(function() { file_name = $("select").val(); $('#span_result').load(file_name); }); }); 

HTML code

 <select class="sel" name="files"> <option value="">Select a file</option> <option value="file.txt">file.txt</option> <option value="file2.txt">file2.txt</option> <option value="jQuery_file.html">jQuery_file.html</option> </select><br> <p>Contents of the file will be displayed below</p> <div id="span_result"></div> 

This worked for me in firefox. Sorry if you failed.

+3
source

All Articles