前端开发网络——Ajax(GET、POST)
生活随笔
收集整理的這篇文章主要介紹了
前端开发网络——Ajax(GET、POST)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?ajax請求的過程
我們平時輸入的網址,比如www.baidu.com,就會被解析成14.215.177.39這一串數字,然后發送請求給后臺服務器(客戶端發送http請求)。
服務器會確認你發送的是什么請求,需要請求什么東西(三次握手)。
拿到服務器返回的數據后就傳回給頁面了,這時候就跟服務器告別(四次揮手)。
傳回給瀏覽器渲染頁面(html,css,js)。
?Ajax的實際運作,好比做一個定外賣的過程
封裝Ajax
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>Document</title> 8 </head> 9 <body> 10 <form> 11 <input type="text" name="urername" id="username"> 12 <input type="text" name="age" id="age"> 13 <input type="submit" id="sbm" value="提交"> 14 </form> 15 <ol id="ol"></ol> 16 <button id="btn">請求新聞</button> 17 <!-- Ajax 18 1.瀏覽器 19 2.Ajax對象 20 3.Ajax.open(method, url, true); 21 4.Ajax.send(); 22 5.onreadtstatechage 4 23 6.status == 200 403 503 --> 24 25 <script> 26 //請求新聞的監聽事件 27 btn.onclick = function(){ 28 ajaxFunc('GET', './getNews.php', '', showList, true); 29 } 30 31 //請求form表單的監聽事件 32 sbm.onclick = function(e){ 33 e.preventDefault();//取消默認提交form表單的事件 34 var data = 'username=' + username.value + '&age=' + age.value; 35 ajaxFunc('POST', './post.php', data, showPerson, true); 36 } 37 38 39 40 //封裝的Ajax函數 41 function ajaxFunc(method, url, data, callback, flag){ 42 43 //創建Ajax對象 44 var xhr = null; 45 if(window.XMLHttpRequest){//瀏覽器兼容 46 xhr = new XMLHttpRequest(); 47 }else{ 48 xhr = new ActiveXObject('Microsoft.XMLHttp'); 49 } 50 51 method = method.toUpperCase(); 52 if(method == 'GET'){//判斷傳入的是GET請求還是POST請求 53 //向后端發送請求,獲取數據 54 xhr.open(method, url, + '?' + data, flag);//請求方式 請求地址 異步請求 55 //把Ajax發送出去 56 xhr.send(); 57 }else if(method == 'POST'){ 58 //向后端發送請求,獲取數據 59 xhr.open(method, url, flag);//請求方式 請求地址 異步請求 60 //設置請求頭 61 xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); 62 //把Ajax發送出去 63 xhr.send(data); 64 } 65 66 //監聽返回的數據 數據解析分為4個階段 1.讀取 2.已讀取 3.交互中 4.完成 67 xhr.onreadystatechange = function(){ //數據狀態改變一次就會觸發一次 68 if(xhr.readyState == 4){ //數據是不是為4的狀態,4為響應內容解析完成 69 if(xhr.status == 200){ 70 71 callback(xhr.responseText); 72 } 73 } 74 } 75 } 76 77 //GET請求的回調函數 78 function showList(data){ 79 var value = JSON.parse(data); 80 var str = ''; 81 value.forEach(function(ele, index){ 82 str += '<li>' + ele.title + '-' + ele.date + '</li>'; 83 }) 84 ol.innerHTML = str; 85 } 86 87 88 //POST請求的回調函數 89 function showPerson(data){ 90 alert(data); 91 } 92 </script> 93 </body> 94 </html>------------------------------------------------------
get:主要用來獲取數據的。
post:主要用來往后端傳數據的
轉載于:https://www.cnblogs.com/yangpeixian/p/11117873.html
總結
以上是生活随笔為你收集整理的前端开发网络——Ajax(GET、POST)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中值传递和引用传递
- 下一篇: 浏览器记住密码的自动填充Input问题完