2011-06-24 109 views
41

我想加載* .txt文件並將內容插入div。 這裏我的代碼:jQuery:加載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> 

TXT:

im done 

如果我按一下按鈕螢火蟲報告以下錯誤:

Syntax-Error 
im done 

我不知道該怎麼辦:-(

+0

使用@Dogbert的答案。暫時忽略錯誤消息。這只是一種「鬼魂」錯誤,如果您嘗試在http服務器上執行代碼,它將會消失。這是瀏覽器的抱怨,你試圖做的是爲http://,而不是file:///。 – IamGuest

回答

56

您需要添加一個數據類型 - http://api.jquery.com/jQuery.ajax/

$(document).ready(function() { 
    $("#lesen").click(function() { 
     $.ajax({ 
      url : "helloworld.txt", 
      dataType: "text", 
      success : function (data) { 
       $(".text").html(data); 
      } 
     }); 
    }); 
}); 
+0

現在他做了我想要的,但是錯誤仍然會報告。 – Khazl

+0

@Khazl,什麼是確切的錯誤信息。你能複製和粘貼嗎? – Dogbert

+0

f(a = div.text, (a = div.text,c =「fxqueue」,d = function()) f()jquery .... min.js(Zeile 16(c =「fxqueue」,d = undefined,e = true) ) f(a = [div.text],c = function(),d = undefined) f(a = function(),b = undefined)f(a =「fx」,c = function f(e = Object {url =「helloworld.txt」,isLocal = true,mehr ...},f = 0(f = [「im完成」,「成功」,對象{readyState = 4,responseXML =文件,更多...}]) g(a = 200,c =「success」,l = Object {xml = document,text =「im done」},m =「」) g(a = readystatechange,e = undefined) im完成 – Khazl

0

嘗試

$(".text").text(data); 

或將接收到的數據轉換爲字符串。

+0

這個報告同樣的錯誤:-( – Khazl

2

您可以使用jQuery load方法獲取內容和插入的元素。

試試這個:

$(document).ready(function() { 
     $("#lesen").click(function() { 
       $(".text").load("helloworld.txt"); 
    }); 
}); 

您,還可以添加一個回調來執行的東西一旦負載過程完成

e.g:

$(document).ready(function() { 
    $("#lesen").click(function() { 
     $(".text").load("helloworld.txt", function(){ 
      alert("Done Loading"); 
     }); 
    }); 
}); 
4

.load("file.txt")要容易得多。哪些工作,但即使測試,您不會從本地驅動器獲得結果,您將需要一個實際的http服務器。看不見的錯誤是XMLHttpRequest錯誤。

0
<script type="text/javascript">  
    $("#textFileID").html("Loading...").load("URL TEXT"); 
</script> 

<div id="textFileID"></div>