jQuery: load txt file and insert into div

2019-01-01 13:37发布

问题:

I want to load a *.txt file and insert the content into a div. Here my code:

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

If i click on the button firebug report following error:

Syntax-Error
im done

I don´t know what to do :-(

回答1:

You need to add a dataType - http://api.jquery.com/jQuery.ajax/

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


回答2:

You could use jQuery.load(): http://api.jquery.com/load/

Like this:

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


回答3:

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 XMLHttpRequest error.



回答4:

You can use jQuery load method to get the contents and insert into an element.

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


回答5:

Try

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

Or to convert the data received to a string.



回答6:

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

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