source

jQuery: txt 파일을 로드하여 div에 삽입합니다.

itover 2023. 2. 11. 09:14
반응형

jQuery: txt 파일을 로드하여 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>

txt:

im done

fire bug report 버튼을 클릭하면 다음 오류가 발생합니다.

Syntax-Error
im done

어떻게 하면 좋을지 모르겠다:-

data Type을 추가해야 합니다(http://api.jquery.com/jQuery.ajax/

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

jQuery.load()를 사용할 수 있습니다.http://api.jquery.com/load/

다음과 같이 합니다.

$(".text").load("helloworld.txt");

.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");
        });
   }); 
}); 

해라

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

또는 수신한 데이터를 문자열로 변환합니다.

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

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

언급URL : https://stackoverflow.com/questions/6470567/jquery-load-txt-file-and-insert-into-div

반응형