jQuery 如何使用jquery加载方法将文件内容加载到变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11583271/
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 to load the content of a file into variable using jquery load method?
提问by Yetimwork Beyene
How do I load the content of a file into a variable instead of the DOM using jQuery .load()
method?
如何使用 jQuery.load()
方法将文件内容加载到变量而不是 DOM 中?
For example,
例如,
$("#logList").load("logFile", function(response){ });
Instead of loading the file into the #logList
element of the DOM, I would like it to load into a variable.
#logList
我希望将文件加载到变量中,而不是将文件加载到DOM的元素中。
回答by adeneo
load()
is just a shortcut for $.get
that atuomagically inserts the content into a DOM element, so do:
load()
只是$.get
自动将内容插入 DOM 元素的快捷方式,所以这样做:
$.get("logFile", function(response) {
var logfile = response;
});
回答by kapa
You can use $.get()
to initiate a GET request. In the success callback, you can set the result to your variable:
您可以使用$.get()
来发起 GET 请求。在成功回调中,您可以将结果设置为您的变量:
var stuff;
$.get('logFile', function (response) {
stuff = response;
});
Please note that this is an asynchronous operation. The callback function will run when the operation is completed, so commands after $.get(...)
will be executed beforehand.
请注意,这是一个异步操作。回调函数会在操作完成时运行,所以之后的命令$.get(...)
会提前执行。
That's why the following will log undefined
:
这就是为什么会记录以下内容undefined
:
var stuff;
$.get('logFile', function (var) {
stuff = var;
});
console.log(stuff); //undefined