【HTML5】用 jQuery(Ajax) 读取本地文本文档并替换 html 元素内容
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Read Local File and Replace Content</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
    <div id="content">
        <!-- 这里的内容将被替换 -->
        这里是原始内容。
    </div>
 
    <script>
        $(document).ready(function() {
            $.ajax({
                url: 'example.txt', // 本地文本文件的路径
                dataType: 'text',
                success: function(data) {
                    $('#content').html(data); // 用读取的内容替换div元素的内容
                },
                error: function(error) {
                    console.error('读取本地文件出错:', error);
                }
            });
        });
    </script>
</body>
</html>在这个例子中,我们使用 jQuery 的 $.ajax() 方法来异步读取本地的 example.txt 文本文件。成功读取文件后,使用 jQuery 的 #content 选择器找到页面中的元素,并用 html(data) 方法将读取到的文本内容替换原有内容。如果读取文件发生错误,将错误信息输出到控制台。这个例子演示了如何在不需要用户上传文件到服务器的情况下,直接在客户端读取本地文本文件并进行操作。
评论已关闭