How can I load a local file using jQuery? (with file://)

前端 未结 2 470
时光说笑
时光说笑 2021-01-18 03:10

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         


        
相关标签:
2条回答
  • 2021-01-18 03:35

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

    0 讨论(0)
  • 2021-01-18 03:37

    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.

    0 讨论(0)
提交回复
热议问题