[英]jQuery: load txt file and insert into div
我想加載一個 *.txt 文件並將內容插入到 div 中。 這是我的代碼:
js:
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
success : function (data) {
$(".text").html(data);
}
});
});
});
html:
<div class="button">
<input type="button" id="lesen" value="Lesen!" />
</div>
<div class="text">
Lorem Ipsum <br />
</div>
文本:
im done
如果我點擊按鈕螢火蟲報告以下錯誤:
Syntax-Error
im done
我不知道該怎么辦 :-(
您需要添加一個數據類型 - http://api.jquery.com/jQuery.ajax/
$(document).ready(function() {
$("#lesen").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
});
});
.load("file.txt")
更容易。 哪個有效,但即使進行測試,您也不會從本地驅動器獲得結果,您需要一個實際的 http 服務器。 不可見的錯誤是XMLHttpRequest
錯誤。
您可以使用 jQuery load方法獲取內容並插入到元素中。
嘗試這個:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt");
});
});
您還可以添加回調以在加載過程完成后執行某些操作
例如:
$(document).ready(function() {
$("#lesen").click(function() {
$(".text").load("helloworld.txt", function(){
alert("Done Loading");
});
});
});
<script type="text/javascript">
$("#textFileID").html("Loading...").load("URL TEXT");
</script>
<div id="textFileID"></div>
嘗試
$(".text").text(data);
或者將接收到的數據轉換為字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.