已上傳至githubhttps://github.com/hajnalmin/ajaxJS.git
如果對你有幫助的話,就去給個星吧~么么噠~筆芯
ajax:一種請求數據的方式,不需要刷新整個頁面;
ajax的技術核心是 XMLHttpRequest 對象;
ajax 請求過程:創建 XMLHttpRequest 對象、連接服務器、發送請求、接收響應數據;
調試過程中需要搭建apache服務
HTML文件如下:(有詳細的注釋)
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>原生js的ajax</title> 6 </head> 7 <body> 8 <!-- 9 原生js封裝ajax方法 10 11 --> 12 13 <script> 14 //1.處理get請求 15 function ajax(option){ 16 //1.實例化ajax 17 18 var xhr = window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("microsoft.xmlhttp"); 19 20 //2.判斷請求方式是否為get 21 var isGET = /get/i.test(option.method); 22 23 24 //3. 將json數據轉換為字符串格式 屬性名=值&。。。 25 var data = ""; 26 for(var i in option.data){ 27 //4.將數據拼成字符串 28 data +=i+"="+ option.data[i]+"&"; 29 } 30 31 //5.將處理好的數據字符串替換原有的數據 32 option.data = data; 33 34 //判斷是否是get方法,如果是檢查url中有沒有?然后再把data數據加到?后 35 if(isGET){ 36 if(option.url.indexOf("?")<0){ 37 option.url+='?'; 38 } 39 option.url+=+"&"+option.data; 40 } 41 42 //6 判斷是否啟用緩存,如果不啟用緩存 添加時間 43 if(!option.cache){ 44 //7向URL上補充時間 45 option.url+="&___="+new Date().getTime(); 46 } 47 //打開連接 48 xhr.open(option.method,option.url,option.async); 49 //7.如果是post請求則設置請求頭 50 if(!isGET){ 51 xhr.setRequestHeader('content-type','application/xml-form-urlencoded'); 52 } 53 54 //8.發送請求 55 xhr.send(option.data); 56 //9.ajax狀態改變時觸發函數 57 xhr.onreadystatechange = function(){ 58 //判斷ajax是否加載完成 59 if(xhr.readyState == 4){ 60 //判斷頁面是否請求成功 61 if(xhr.status == 200){ 62 option.success(xhr.responseText); 63 }else{ 64 option.error(xhr.status) 65 } 66 } 67 68 } 69 70 } 71 72 ajax({ 73 method:'get', 74 url:"01.php?name=Kitty", 75 async:true, 76 data:{age:12,sex:"girl"}, 77 cache:true, 78 sendBefore:function(xhr){ 79 console.log("loading···"); 80 }, 81 sendComplete:function(xhr){ 82 console.log("loading完成"); 83 }, 84 success:function(txt){ 85 console.log("請求成功,服務器返回數據為:"+txt); 86 }, 87 error:function(status){ 88 console.log("請求失敗狀態碼為:"+status); 89 } 90 }); 91 92 </script> 93 </body> 94 </html>
PHP文件如下:(僅做測試用)
<?php echo 'get<pre>'; print_r($_GET); echo 'post<pre>'; print_r($_POST);
運行成功后的顯示:
注意:如果不是在Apache服務器下,會顯示以下信息
有什么問題歡迎交流溝通~大家一起學習~