注意的问题:
1 在服务器中运行测试
2 注意编码的问题,编码要统一,否则读取的信息会乱码
HTML代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> New Document </title> <meta http-equiv="content-type" content="text/html;charset=UTF-8"/> <script type="text/javascript"> function doAjaxCall(the_request) { var request=null; if(window.XMLHttpRequest) { request=new XMLHttpRequest(); }else if(window.ActiveXObject) { request=new ActiveXObject("Microsoft.XMLHTTP"); } if(request) { request.open("GET",the_request,true); request.onreadystatechange=function() { if(request.readyState===4) { if (request.status == 200 || request.status == 0) { document.getElementById("vv").innerHTML=request.responseText; } } } request.send(null); }else{ alert("error"); } } </script> </head> <body> <input type="button" value="make" onclick="doAjaxCall('ajax-1.txt');"/> <div id="vv"></div> </body> </html>
TXT文件内容:
this is the first test
ajax读取文本内容原理较为简单,在核心思想掌握之后,对大型的开发应用是很容易上手的,重点基础是熟悉XMLHTTP对象的属性和方法,对其应用得心应手才会写出用户感受良好的应用。