Javascript 使用 JQuery 或 Ajax 加载 .txt 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11589387/
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
Load .txt file using JQuery or Ajax
提问by atomSmasher
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQueryexplains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
我如何修复下面的脚本,以便它每次都能正常工作!有时它有效,有时它不起作用。Pro JQuery解释了导致这种情况的原因,但没有讨论如何修复它。我几乎肯定它与 ajax 就绪状态有关,但我不知道如何编写它。网络上展示了大约 99 种不同的方式来编写 ajax 和 JQuery,这有点让人不知所措。
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was @#!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
我的目标是创建一个 HTML shell,它可以填充来自基于服务器的文本文件的文本。例如:假设服务器上有一个名为 AG 的文本文件,其内容为 PF:PF-01、PF-02、PF-03 等。我想提取这些信息并在它之前填充 HTML DOM被用户看到。A 是 @#!#$*& 金色的 PHP,然后发现我的主机已关闭 fopen()。所以我来了。
Thanks for you help.
谢谢你的帮助。
JS - plantSeed.js
JS - 植物种子.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
HTML - 头
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
HTML - 正文
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
回答by Novak
Try this:
尝试这个:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
回答by davidbuzatto
Try this:
尝试这个:
HTML:
HTML:
<div id="target"></div>
JavaScript:
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load()
function.
在我的示例中,div 将填充文件内容。看看jQuery.load()
函数。
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
“pathToYourFile”可以是包含要加载的数据的任何资源。查看加载方法文档以获取有关如何使用它的更多信息。
Edit: Other examples to get the value to be manipulated
编辑:获取要操作的值的其他示例
Using $.get()
function:
使用$.get()
功能:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax()
function:
使用$.ajax()
功能:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
需要注意的是:
$(function(){
// code...
});
Is the same as:
是相同的:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
通常您需要使用这种语法,因为您希望 DOM 准备好执行您的 JavaScript 代码。
回答by Norguard
Here's your issue: You've got a script tag in the body, which is asking for the AJAX data. Even if you were asking it to write the data to your shell, and not just spout it... ...that's your #1 issue.
这是您的问题:您在正文中有一个脚本标记,它要求 AJAX 数据。即使您要求它将数据写入您的 shell,而不仅仅是喷出它... ...那是您的第一个问题。
Here's why:
原因如下:
AJAX is asynchronous. Okay, we know that already, but what does that mean?
AJAX 是异步的。好的,我们已经知道了,但这意味着什么?
Well, it means that it's going to go to the server and ask for the file. The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
嗯,这意味着它将去服务器并请求文件。服务器将去寻找,然后将其发回。然后您的计算机将下载内容。当内容 100% 下载后,它们就可以使用了。
...thing is...
……事情是……
Your program isn't waiting for that to happen. It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
您的程序不会等待这种情况发生。它告诉服务器慢慢来,同时它会继续做它正在做的事情,它不会再考虑内容,直到它收到服务器的调用。
Well, browsers are really freakin' fast when it comes to rendering HTML. Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
嗯,浏览器在呈现 HTML 时真的非常快。服务器在提供静态(纯文本/img/css/js)文件方面也非常快。
So now you're in a race. Which will happen first? Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
所以现在你在比赛中。哪个会先发生?服务器会用文本回调,还是浏览器会点击要求文件内容的脚本标签?
Whichever one wins on that refresh is the one that will happen.
无论哪一个在刷新中获胜,都会发生。
So how do you get around that? Callbacks.
那么你如何解决这个问题呢?回调。
Callbacks are a different way of thinking. In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
回调是一种不同的思维方式。在 JavaScript 中,当下载完成时,您通过为 AJAX 调用提供一个要使用的函数来执行回调。
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
这就像从工作热线打电话给某人,然后说:当你有答案时,请拨这个分机联系我。
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); }
a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
在 jQuery 中,您将在 AJAX 调用中使用名为“success”的参数。将success : function (data) { doSomething(data); }
您传递给 AJAX 调用的对象作为一部分。当文件下载时,一旦下载,jQuery 就会将结果传递到您提供给它的成功函数中,该函数将执行它要执行的任何操作,或者调用它要调用的任何函数。
Give it a try. It sure beats racing to see which downloads first.
试一试。它肯定比赛车更能查看首先下载的内容。
回答by blasteralfred Ψ
I recommend not to use url: "./seeds/Ag.txt",
, to target a file directly. Instead, use a server side script llike PHPto open the file and return the data, either in plane format or in JSON format.
我建议不要使用url: "./seeds/Ag.txt",
, 直接定位文件。相反,使用类似PHP的服务器端脚本打开文件并以平面格式或 JSON 格式返回数据。
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php
您可以在此处找到打开文件的教程:http: //www.tizag.com/phpT/fileread.php