同步方法
1 addEvent(document, ‘click‘, function() { 2 var xhr = new XMLHttpRequest(); //create xhr obj 3 xhr.open(‘get‘, ‘time.php?rand=‘+Math.random(), false); //准备发送请求 ,以get方式请求,url是time.php,同步 4 xhr.send(null); //发送请求,get不需要数据提交,则填写null; 5 if (xhr.status == 200) { 6 alert(xhr.responseText); 7 } 8 else { 9 alert(‘错误 状态代码:‘ + xhr.status + ‘状态信息:‘ + xhr.statusText); 10 } 11 })
responseText :作为相应主体被返回文本
responseXML :如果响应主体内容类型是text/xml or application/xml,则返回包含相应数据的XML DOM文档
status :响应HTTP的状态
statusText http:状态说明
异步方法
1 addEvent(document, ‘click‘, function() { 2 var xhr = new XMLHttpRequest(); 3 xhr.onreadystatechange = function() { 4 if (xhr.readyState == 4) { 5 if ((xhr.status == 200 && xhr.status < 300) || xhr.status == 304) { 6 alert(xhr.responseText); 7 } else { 8 alert(‘错误状态代码:‘ + xhr.status + ‘,状态信息:‘ + xhr.statusText); 9 } 10 } 11 }; 12 xhr.open(‘get‘, ‘time.php?rand=‘ + Math.random(), true); 13 xhr.send(null); 14 //xhr.abort() //取消异步 15 })
在Web程序上,GET一般是URL提交请求,比如demo.php?name=lee&age=100
POST 一般是Web表单提交 :比如<form method="post"><input type="text" name="ale" value="100">
注意:
一、如果没有向服务器端发送,firebug无发送提示,如果有send()方法,则firebug会提示发送。
二、通过点击事件,不断的像服务器发送请求,然后服务器时时返回最新数据,就是ajax功能;
三、ie浏览器第一次会向服务器请求,获取最新数据,而第二次它默认获取返回最新数据,导致数据不正确。
处理缓存,可以使用JS随机字符串。
原文:http://www.cnblogs.com/Initial-C/p/5017454.html