【问题标题】:How can I load a local file using jQuery? (with file://)如何使用 jQuery 加载本地文件? (带文件://)
【发布时间】:2016-01-29 09:37:59
【问题描述】:

有没有办法使用 jQuery 从数据文件(例如 JSON .js 文件)加载数据?

例如:

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

目前,JQuery 似乎没有执行简单的 HTTP GET,而是尝试对其执行 OPTIONS 请求,但在 file:// URI 上失败。我只想加载数据,以便可以在离线环境中使用该站点(未安装 Web 服务器)。

【问题讨论】:

标签: jquery


【解决方案1】:

GET 需要 HTTP 连接,因此如果没有本地 Web 服务器,它将无法工作。虽然您可以open and read a file 使用 HTML5,但不能以这种方式加载 JavaScript 资源。

如果页面是在本地加载的,你通常会使用脚本标签来加载 JS。

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

解决这个问题的唯一方法可能是这个答案:Is it possible to load in a local version of a JavaScript file instead of the server version?

this(两者都需要制作本地伪服务器):

【讨论】:

    【解决方案2】:

    我希望这是可能的。我试过了。 Html 代码和文本文件位于同一文件夹中。

    这里是 jQuery 部分。

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

    Html 代码是

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

    它在 Firefox 中对我有用。对不起,如果你失败了。

    【讨论】:

    • 在 Chrome 上,这在 file:// 上失败 - “跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。”正如文档所预期的那样。 api.jquery.com/load "从服务器加载数据"
    • 因为您在本地提供它(因此是 file://)。您需要从 Web 服务器执行此操作。
    猜你喜欢
    • 2013-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2021-05-07
    相关资源
    最近更新 更多