Javascript jQuery:加载txt文件并插入div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6470567/
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
jQuery: load txt file and insert into div
提问by Khazl
I want to load a *.txt file and insert the content into a div. Here my code:
我想加载一个 *.txt 文件并将内容插入到 div 中。这是我的代码:
js:
js:
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
success : function (data) {
$(".text").html(data);
}
});
});
});
html:
html:
<div class="button">
<input type="button" id="lesen" value="Lesen!" />
</div>
<div class="text">
Lorem Ipsum <br />
</div>
txt:
文本:
im done
If i click on the button firebug report following error:
如果我点击按钮萤火虫报告以下错误:
Syntax-Error
im done
I don′t know what to do :-(
我不知道该怎么办 :-(
回答by Dogbert
You need to add a dataType - http://api.jquery.com/jQuery.ajax/
您需要添加一个数据类型 - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});
回答by jncraton
You could use jQuery.load(): http://api.jquery.com/load/
你可以使用 jQuery.load(): http://api.jquery.com/load/
Like this:
像这样:
$(".text").load("helloworld.txt");
回答by andersna75
The .load("file.txt")is much easier. Which works but even if testing, you won't get results from a localdrive, you'll need an actual http server. The invisible error is an XMLHttpRequesterror.
这.load("file.txt")要容易得多。哪个有效,但即使进行测试,您也不会从本地驱动器获得结果,您需要一个实际的 http 服务器。看不见的错误就是XMLHttpRequest错误。
回答by Chandu
You can use jQuery loadmethod to get the contents and insert into an element.
您可以使用 jQuery load方法获取内容并插入到元素中。
Try this:
尝试这个:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
You, can also add a call back to execute something once the load process is complete
您还可以添加回调以在加载过程完成后执行某些操作
e.g:
例如:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
回答by Jose Faeti
Try
尝试
$(".text").text(data);
Or to convert the data received to a string.
或者将接收到的数据转换为字符串。
回答by Elon Gomes Vieira
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>

