<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> // get()请求 if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else { xhr=new ActiveXObject('Microsoft.XMLHTTP')// 兼容低版本ie } xhr.open("get","1.get.php?username=李&age=12",true); xhr.send(); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ document.write(xhr.responseText) } } } // post()请求 if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else { xhr=new ActiveXObject('Microsoft.XMLHTTP')// 兼容低版本ie } xhr.open("post","1.post.php",true); xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send('username=李&age=12'); xhr.onreadystatechange=function() { if (xhr.readyState == 4) { if (xhr.status == 200) { document.write(xhr.responseText) }else if(x.status==404){ document.write("404") } } }
// ajax 封装post和get(单独建个JS文件用<script src=''>引用) function ajax(method,url,boolean,date,fn) { var xhr=null // post()请求 if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else { xhr=new ActiveXObject('Microsoft.XMLHTTP')// 兼容低版本ie6 } if(method=='post'){ xhr.open('post',url,true); xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(date); }else { // get()请求 xhr.open('get',url+"?"+date,true); xhr.send(); } xhr.onreadystatechange=function() { if (xhr.readyState == 4&&xhr.status == 200) { fn(xhr.responseText) } } }
</script></body></html>