如何使用 jQuery 加载本地文件?(带文件://)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14507677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I load a local file using jQuery? (with file://)
提问by NickG
Is there any way to load data from a data file (eg a JSON .js file) using jQuery?
有没有办法使用 jQuery 从数据文件(例如 JSON .js 文件)加载数据?
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).
目前,JQuery 似乎并没有执行简单的 HTTP GET,而是尝试对其执行 OPTIONS 请求,但在 file:// URI 上失败。我只想加载数据,以便该站点可以在离线环境中使用(未安装 Web 服务器)。
采纳答案by Diodeus - James MacFarlane
GET requires an HTTP connection, so without a local web servber it won't work. While you can open and read a fileusing HTML5, you can't load a JavaScript resource that way.
GET 需要一个 HTTP 连接,所以如果没有本地网络服务器,它就无法工作。虽然您可以使用 HTML5打开和读取文件,但不能以这种方式加载 JavaScript 资源。
If the page is loaded locally, you'd usually load the JS using a script tag.
如果页面是在本地加载的,您通常会使用脚本标记加载 JS。
<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?
解决此问题的唯一方法可能是在此答案中:是否可以加载本地版本的 JavaScript 文件而不是服务器版本?
or this(both require making a local pseudo-server) :
或者这个(两者都需要制作一个本地伪服务器):
回答by Kishore K
I hope it is possible. I'd tried it. the Html code and text files resides in the same folder.
我希望这是可能的。我试过了。Html 代码和文本文件位于同一文件夹中。
Here is jQuery part.
这是 jQuery 部分。
$(document).ready(function()
{
$("select").change(function()
{
file_name = $("select").val();
$('#span_result').load(file_name);
});
});
The Html code is
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>
Itworked for me in firefox. Sorry if it failed with you.
它在 Firefox 中对我有用。对不起,如果你失败了。