1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>修改内容</title>
6 <!--
7 所有现代浏览器均支持XMLHttpRequest对象(IE6 IE5使用ActiveXObject)
8 XMLHttpRequest用于在后台与服务器交换数据,这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新
9 创建XMLHttpRequest对象
10 IE7+ FireFox chrome Opera Safari
11 xmlhttp = new XMLHttpRequest();
12 IE5 IE6
13 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
14
15 -->
16 <script>
17 function loadXMLDoc() {
18 var xmlhttp;
19 if (window.XMLHttpRequest) {
20 //code for IE7+ FireFox chrome Opera Safari
21 xmlhttp = new XMLHttpRequest();
22 } else {
23 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
24 }
25 /**
26 * 当使用async=true时,请规定在想赢处于onreadystatechange事件中的就绪状态时执行的函数
27 * 如果async=false时就不必使用onreadystatechange函数,将代码放到send()语句之后即可
28 * xmlhttp.open("GET","ajax_info.txt",false);
29 *xmlhttp.send();
30 *document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
31 * */
32 xmlhttp.onreadystatechange = function () {
33 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
34 document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
35 }
36 }
37 //open(method,url,async):
38 //method :规定请求的类型 GET或POST
39 //url : 文件在服务器上的位置
40 //async:true为异步 false为同步
41 xmlhttp.open("GET", "../ajax_info.txt", true);
42 //send(string)将请求发送到服务器 带有string参数的仅用于POST请求
43 /**
44 * 与POST想比GET更简单也更快,并且在大部分情况下都能使用
45 * 然而在以下情况下请使用POST请求:
46 * 无法使用缓存文件(更新服务器上的文件或数据库)
47 * 向服务器发送大量数据(POST没有数据量限制)
48 * 发送包含未知字符的用户输入时POST比GET更稳定也更可靠
49 * 使用POST请求时如果需要HTML表单那样POST数据,请使用setRequestHeader()来添加HTTP头然后在send()方法中规定希望发送的数据
50 * xmlhttp.open("POST","ajax_test.html",true);
51 *xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
52 *xmlhttp.send("fname=Henry&lname=Ford");
53 * sendRequestHeader(header,value) header:规定头的名称 value:规定头的值
54 *
55 * */
56
57 xmlhttp.send();
58
59 }
60 </script>
61 </head>
62 <body>
63 <div id="myDiv">
64 <h2>使用Ajax修改该文本的内容</h2>
65 </div>
66 <button type="button" onclick="loadXMLDoc()">修改内容</button>
67 </body>
68 </html>