// ajax get 五部曲 function ajax_get(url,data){ var ajax=new XMLHttpRequest();
//url方法,如果发送数据段格式为xxx。php?name=jack&age=18,需要拼接 if(data){ url+='?'; url+=data;
}else{ } ajax.open('get',url); ajax.send(); ajax.onreadystatechange=function(){
if(ajax.readyState==4&&ajax.status==200){ console.log(ajax.responseText); } } }
function ajax_post(url,data){ var ajax=new XMLHttpRequest();
ajax.open('post',url);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
if(data){ ajax.send(data); }else{ ajax.send(); }
ajax.onreadystatechange=function(){ if(ajax.readyState==4&&ajax.status==200){
console.log(ajax.responseText); } } } //将get和post封装到一起 function
ajax_tool(url,data,method,success){ var ajax=new XMLHttpRequest();
if(method=='get'){ if(data){ url+='?'; url+=data; }else{ }
ajax.open(method,url); ajax.send(); }else{ //post请求不需要改变 ajax.open(method,url);
ajax.setRequestHeader("Content-type","x-www-form-urlencoded"); if(data){
ajax.send(data); }else{ ajax.send(); } } ajax.onreadystatechange=function(){
if(ajax.readyState==4&&ajax.status==200){ console.log(ajax.responseText);
//将数据让外边可以使用 return ajax.responseText; // 当 onreadystatechange 调用时 说明 数据回来了 //
ajax.responseText; success(ajax.responseText); } } }
引用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8">
<title>Document</title> </head> <body> <input type="button" value="测试get"
id="ajax_get"> </body> </html> <!-- 导入封装的JS --> <script type="text/javascript"
src="ajax_tool.js"></script> <script type="text/javascript">
document.querySelector("#ajax_get").onclick=function(){ var
backData=ajax_tool('01.test_get.php','name=huluwa&&skill=saveyeye','get',function(data){
console.log(data); }); console.log(backData); } </script> <?php // 获取get提交的数据
echo $_GET['skill']; ?>