8

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

eg:

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

At the moment, instead of doing a simple HTTP GET, JQuery appears to be trying to do an OPTIONS request on it, which fails on a file:// URI. I just want to load the data in so that the site can be used in an offline environment (without a web server installed).

NickG
  • 9,315
  • 16
  • 75
  • 115
  • 1
    Possible duplicate: http://stackoverflow.com/questions/4408707/jquery-read-text-file-from-file-system – aurbano Jan 24 '13 at 18:03

2 Answers2

5

GET requires an HTTP connection, so without a local web servber it won't work. While you can open and read a file using HTML5, you can't load a JavaScript resource that way.

If the page is loaded locally, you'd usually load the JS using a script tag.

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

The only way around this may be in this answer: Is it possible to load in a local version of a JavaScript file instead of the server version?

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

Community
  • 1
  • 1
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
4

I hope it is possible. I'd tried it. the Html code and text files resides in the same folder.

Here is jQuery part.

$(document).ready(function()
{
    $("select").change(function()
    {


        file_name = $("select").val();
        $('#span_result').load(file_name);
    });
});

The Html code is

<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>

Itworked for me in firefox. Sorry if it failed with you.

Kishore K
  • 2,425
  • 4
  • 18
  • 18
  • 7
    On Chrome, this fails on file:// - "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource." As expected from the docs. http://api.jquery.com/load/ "Load data from the server" – ChrisJJ Oct 05 '16 at 11:07
  • 1
    Because you're serving it locally (hence file://). You need to do this from a web server. – Tyler Montney May 07 '18 at 17:49