整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          Ajax GET和POST模式

          Ajax GET和POST模式

          ET和POST的區別

          1 get請求將參數放到請求地址url的后面

          post請求時將參數放在http請求空白行的后面

          2 get請求時參數大小有限制(2K)

          post請求理論上對參數大小無限制

          3 post比get安全一些

          4 post請求時,除了參數格式不同之外, 還比get請求多了一個Content-type的請求頭,它的值是application/x-www-form-urlencoded,

          表示本次提交的數據是字符數據, 同時post還可以同時提交二進制數據和字符數據, 如:multipart/form-data

          ajax發送請求其實就是模擬http請求

          ajax對象的post請求也要加上content-type的請求頭。

          ajax發送數據是采用UTF-8編碼的方式發送的, 所以在PHP中應用ajax技術應及時進行編碼轉換;

          GET模式

          GET模式步驟:

          創建ajax對象xmlHttp

          生成URL

          setRequestHeader("If-Modified-Since","0");//解決IE緩存的第三種方法
          xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
              //..xmlHttp.responseText..
            }};
          xmlhttp.open("GET",URL);
          xmlHttp.send(null);
          <!DOCTYPE html>
          <html>
          <head>
          <title>GET VS. POST</title>
          <script language="javascript">
          var xmlHttp;
          function createXMLHttpRequest(){
                  if(window.ActiveXObject)
                  xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
                  else if(window.XMLHttpRequest)
                  xmlHttp=new XMLHttpRequest();
          }
          function createQueryString(){
                  var firstName=document.getElementById("firstName").value;
                  var birthday=document.getElementById("birthday").value;
                  var queryString="firstName=" + firstName + "&birthday=" + birthday;
                  return encodeURI(encodeURI(queryString)); //兩次編碼解決中文亂碼問題
          }
          function doRequestUsingGET(){
                  createXMLHttpRequest();
                  var queryString="sync.php?";
                  queryString +=createQueryString() + "×tamp=" + new Date().getTime();
                  xmlHttp.onreadystatechange=handleStateChange;
                  xmlHttp.open("GET",queryString);
                  xmlHttp.send(null);
          }
          function handleStateChange(){
                  if(xmlHttp.readyState==4 && xmlHttp.status==200){
                          var responseDiv=document.getElementById("serverResponse");
                          responseDiv.innerHTML=decodeURI(xmlHttp.responseText); //解碼
                  }
          }
          </script>
          </head>
          <body>
          <h2>輸入姓名和生日</h2>
          <form>
          <input type="text" id="firstName" /><br>
          <input type="text" id="birthday" />
          </form>
          <form>
          <input type="button" value="GET" onclick="doRequestUsingGET();" /><br>
          </form>
          <div id="serverResponse"></div>
          </body>
          </html>

          服務器端代碼(文件名:sync.php)

          <?php
          header("Cache-Control: no-cache, must-revalidate"); //解決IE緩存采用第四種方式
          header('Content-type: text/html;charset=utf-8');
          echo "GET: " . $_GET["firstName"] . ", your birthday is " . $_GET["birthday"];
          ?>

          解決異步連接服務器時IE的緩存問題(GET模式)

          隨機數:Math.random();

          var sUrl="sync.php?name=zhangsan" + Math.random();//地址不斷的變化,此種方法會把Math.random()數據一并返回

          var sUrl="sync.php?name=zhangsan&random=" + Math.random();

          缺點:隨機數默認返回的是0-1之間的小數, 因為是隨機產生的, 也有可能出現重合的情況, 雖然概率很低。


          時間:new Date().getTime();

          var sUrl="sync.php?" + new Date().getTime(); //地址不斷的變化,此種方法會把new Date().getTime()數據一并返回,故不應該采用
          var sUrl="sync.php?name=zhangsan×tamp=" + new Date().getTime();
          xmlHttp.open("GET",sUrl,true);
          setRequestHeader("If-Modified-Since","0"); //此語句放在xmlHttp.open()語句后面

          這種方法設置ajax對象的請求頭 if-modified-since, 強制讓ajax對象發送請求

          0:表示文件最后修改時間, 會和服務器上這個資源文件最后修改時間進行比較, 時間不一致, 所以服務器返回了最新數據。

          以上三種方式并沒有根本上解決緩存問題, 前二種方式更是緩存下來N個文件。

          header("Cache-Control:no-cache,must-revalidate");

          設置http響應頭中的cache-control選項,"告訴"瀏覽器:你不要緩存, 必須每次重新請求。

          POST模式

          POST模式步驟:

          創建ajax對象xmlHttp

          生成URL

          xmlHttp.open("post","action.php");   // POST請求 action.php 后面沒有參數
          xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

          設置請求頭信息:content-type:傳送數據的數據類型 application/x-www-form-urlencoded :表示數據是字符串數據

          xmlHttp.onreadystatechange=function(){
            if(xmlHttp.readyState==4 && xmlHttp.status==200){
              //..xmlHttp.responseText..
            }
          };
          xmlHttp.send(data);

          data:會自動將參數放到請求空白行的后面

          注意:ajax對象的POST請求模式不會產生緩存問題

          完整實例:

          <!DOCTYPE html>
          <html>
          <head>
          <title>GET VS. POST</title>
          <script language="javascript">
                var xmlHttp;
                function createXMLHttpRequest(){
                        if(window.ActiveXObject)
                        xmlHttp=new ActiveXObject("Microsoft.XMLHttp");
                        else if(window.XMLHttpRequest)
                        xmlHttp=new XMLHttpRequest();
                }
                function createQueryString(){
                        var firstName=document.getElementById("firstName").value;
                        var birthday=document.getElementById("birthday").value;
                        var queryString="firstName=" + firstName + "&birthday=" + birthday;
                        return encodeURI(encodeURI(queryString)); //兩次編碼解決中文亂碼問題
                }
                function doRequestUsingPOST(){
                        createXMLHttpRequest();
                        var url="sync.php?timestamp=" + new Date().getTime();
                        var queryString=createQueryString();
                        xmlHttp.onreadystatechange=handleStateChange;
                        xmlHttp.open("POST",url);
                        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                        xmlHttp.send(queryString); //該語句負責發送數據
                }
                function handleStateChange(){
                        if(xmlHttp.readyState==4 && xmlHttp.status==200){
                        var responseDiv=document.getElementById("serverResponse");
                        responseDiv.innerHTML=decodeURI(xmlHttp.responseText); //解碼
                        }
                }
          </script>
          </head>
          <body>
          <h2>輸入姓名和生日</h2>
          <form>
          <input type="text" id="firstName" /><br>
          <input type="text" id="birthday" />
          </form>
          <form>
          <input type="button" value="POST" onclick="doRequestUsingPOST();" />
          </form>
          <div id="serverResponse"></div>
          </body>
          </html>

          服務器端代碼(文件名:sync.php)

          <?php
                  header('Content-type: text/html;charset=utf-8');
                  echo "POST: " . $_POST["firstName"] . ", your birthday is " . $_POST["birthday"];
          ?>

          注意:發送中文字符易出現亂碼問題,這是因為異步對象xmlhttp在處理返回的responseText的時候,是按UTF-8編碼進行解碼的,

          而網頁的編碼方式與UTF-8不一致。通常的解決方法是用encodeURL()和decodeURL(),必須對發送的數據進行兩次encodeURL()編碼,

          代碼如下:

          function createQueryString(){
                  var firstName=document.getElementById("firstName").value;
                  var birthday=document.getElementById("birthday").value;
                  var queryString="firstName=" + firstName + "&birthday=" + birthday;
                  return encodeURI(encodeURI(queryString)); //兩次編碼解決中文亂碼問題
          }

          而且在返回數據responseText時再進行一次解碼,代碼如下:

          function handleStateChange(){
                  if(xmlHttp.readyState==4 && xmlHttp.status==200){
                          var responseDiv=document.getElementById("serverResponse");
                          responseDiv.innerHTML=decodeURI(xmlHttp.responseText); //解碼
                  }
          }

          第二種方法:對ajax傳送過來的數據進行轉碼

          <?php
          header("content-type:text/html;charset=gb2312");
          echo "POST:".iconv("utf-8","gb2312",$_POST['firstName']).",your birthday is ".iconv("utf-8","gb2312",$_POST['birthday']);
          ?>

          注意:以上資料涉及到HTTP狀態協議使用HttpWatch軟件(強大的網頁數據分析工具)查看

          POST和GET請求主要是客戶端瀏覽器向服務器端發送的請求信息

          在HttpWatch軟件的Stream(流)的左邊

          左邊:客戶端向服務器端發送數據流

          兩次對中文編碼encodeURI可以用encodeURIComponent代替

          *管理員登陸

          1.前臺頁面 :用戶名 密碼 登陸放在form中

          1.2.用戶輸入可以提交: 提交到那個頁面action 提交方式 method=get post 默認提交參數方式是get

          1.3.確定提交參數 加上name屬性 不一定需要些數據庫字段,但是為了方便簡潔編寫代碼,統一要求和數據庫字段名保持一致

          /*get和post區別

          共同點:都可以用來傳遞參數,默認表單傳遞參數是get方式

          //?username=21321&password=213213&email

          1.get方式:通過?傳遞參數 多個參數用&拼接 ?前面就是頁面訪問路徑 明文傳遞 安全性低 傳遞參數最大值是3KB

          2.POST:傳遞的參數隱藏在頭部信息里面 匿名傳遞 安全系數高 傳參最大值8M

          */

          /*2.后臺

          2.1定義變量接受用戶提交的值 用戶提交的值被存儲到了$_GET或者 $_POST兩個預定數組(數組一定存在,并且可以為空可以有值)中

          2.1.1防止頁面報錯找不到username password 我們需要判斷empty() isset();

          /*empty()與isset()的區別

          empty()判斷它是否為空 true 未定義 0 null array false

          isset() 判斷一個值是否存在 null 未定義

          */

          //print_r($_POST);//array() 空數組

          //print_r($_POST['username']);//Array ( [username]=> 123 [password]=> 123 )

          //print_r($_POST['password']);

          /*3.連接數據庫 和數據庫中相應的表進行匹配,倘若用戶輸入的值和數據庫匹配成功跳轉*/

          if(!empty($_POST)){

          $username=$_POST['username'];

          $password=md5($_POST['password']);//密碼需要加密 MD5

          //連接數據庫

          $link=mysql_connect('localhost','root','');

          if(!$link){

          die(mysql_error());//連接失敗,報錯,終止

          }

          //選擇數據庫

          if(!mysql_select_db('1501_cms')){

          die(mysql_error());//連接失敗,報錯,終止

          }

          //設置傳輸編碼

          mysql_query('set names utf8');

          //編寫SQL語句

          $sql="select * from `admin` where username='$username' and password='$password'";

          //發送SQL語句

          $query=mysql_query($sql);

          $assoc=mysql_fetch_assoc($query);//從結果集中獲取一行作為關聯數組

          if($assoc){

          //js跳轉方式 可以增加用戶體驗 但是需要向服務器發送兩次請求 安全性不是很高

          //echo '<script>alert("恭喜您。登陸成功");window.location.href="index.html"</script>';

          //php方式直接改變url地址欄中的地址 速度快 用戶體驗差

          //http://localhost/1501/index.html 絕對地址 中國湖北省武漢市洪山區魯磨路聯峰大廈1203室第一排

          //相對于當前文件跳轉那個頁面 相對地址 左前方

          header('location:http://localhost/1501/index.html');

          }else{

          echo '請輸入正確的用戶名和密碼';

          }

          }

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

          <html xmlns="http://www.w3.org/1999/xhtml">

          <head>

          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

          <title>Simpla Admin | Sign In by www.865171.cn</title>

          <!-- CSS -->

          <!-- Reset Stylesheet -->

          <link rel="stylesheet" href="resources/css/reset.css" type="text/css" media="screen" />

          <!-- Main Stylesheet -->

          <link rel="stylesheet" href="resources/css/style.css" type="text/css" media="screen" />

          <!-- Invalid Stylesheet. This makes stuff look pretty. Remove it if you want the CSS completely valid -->

          <link rel="stylesheet" href="resources/css/invalid.css" type="text/css" media="screen" />

          <!-- Javascripts -->

          <!-- jQuery -->

          <script type="text/javascript" src="resources/scripts/jquery-1.3.2.min.js"></script>

          <!-- jQuery Configuration -->

          <script type="text/javascript" src="resources/scripts/simpla.jquery.configuration.js"></script>

          <!-- Facebox jQuery Plugin -->

          <script type="text/javascript" src="resources/scripts/facebox.js"></script>

          <!-- jQuery WYSIWYG Plugin -->

          <script type="text/javascript" src="resources/scripts/jquery.wysiwyg.js"></script>

          </head>

          <body id="login">

          <div id="login-wrapper" class="png_bg">

          <div id="login-top">

          <h1>Simpla Admin</h1>

          <!-- Logo (221px width) -->

          <a ><img id="logo" src="resources/images/logo.png" alt="Simpla Admin logo" /></a> </div>

          <!-- End #logn-top -->

          <div id="login-content">

          <form action="" method="post">

          <div class="notification information png_bg">

          <div> Just click "Sign In". No password needed. </div>

          </div>

          <p>

          <label>Username</label>

          <input class="text-input" type="text" name="username" />

          </p>

          <div class="clear"></div>

          <p>

          <label>Password</label>

          <input class="text-input" type="password" password="password" />

          </p>

          <div class="clear"></div>

          <p id="remember-password">

          <input type="checkbox" />

          Remember me </p>

          <div class="clear"></div>

          <p>

          <input class="button" type="submit" value="Sign In" />

          </p>

          </form>

          </div>

          <!-- End #login-content -->

          </div>

          <!-- End #login-wrapper -->

          </body>

          </html>

          、如果vue想做交互,引入: vue-resouce

          二、get方式

          1、get獲取一個普通文本數據:

          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
           </style>
           <script src="vue.js"></script>
           <script src="vue-resource.js"></script>
           <script>
           window.onload=function(){
           new Vue({
           el:'body',
           data:{
           },
           methods:{
           get:function(){
           this.$http.get('a.txt').then(function(res){
           alert(res.status);//成功
           alert(res.data);
           },function(res){
           alert(res.status);//失敗返回
           alert(res.data);
           });
           }
           }
           });
           };
           </script>
          </head>
          <body>
           <input type="button" value="按鈕" @click="get()">
          </body>
          </html>
          

          2、get給服務發送數據:

          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
           </style>
           <script src="vue.js"></script>
           <script src="vue-resource.js"></script>
           <script>
           window.onload=function(){
           new Vue({
           el:'body',
           data:{
           },
           methods:{
           get:function(){
           this.$http.get('get.php',{
           a:1,
           b:2
           }).then(function(res){
           alert(res.data);
           },function(res){
           alert(res.status);
           });
           }
           }
           });
           };
           </script>
          </head>
          <body>
           <input type="button" value="按鈕" @click="get()">
          </body>
          </html>
          

          三、post方式

          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
           </style>
           <script src="vue.js"></script>
           <script src="vue-resource.js"></script>
           <script>
           window.onload=function(){
           new Vue({
           el:'body',
           data:{
           },
           methods:{
           get:function(){
           this.$http.post('post.php',{
           a:1,
           b:20
           },{
           emulateJSON:true
           }).then(function(res){
           alert(res.data);
           },function(res){
           alert(res.status);
           });
           }
           }
           });
           };
           </script>
          </head>
          <body>
           <input type="button" value="按鈕" @click="get()">
          </body>
          </html>
          

          四、jsonp方式

          獲取百度接口



          查看響應數據



          jsonp請求百度接口

          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
           </style>
           <script src="vue.js"></script>
           <script src="vue-resource.js"></script>
           <script>
           window.onload=function(){
           new Vue({
           el:'body',
           data:{
           },
           methods:{
           get:function(){
           this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
           wd:'a'
           },{
           jsonp:'cb'//回調函數名稱
           }).then(function(res){
           alert(res.data.s);
           },function(res){
           alert(res.status);
           });
           }
           }
           });
           };
           </script>
          </head>
          <body>
           <input type="button" value="按鈕" @click="get()">
          </body>
          </html>
          

          jsonp請求360接口

          <!DOCTYPE html>
          <html lang="en">
          <head>
           <meta charset="UTF-8">
           <title></title>
           <style>
           </style>
           <script src="vue.js"></script>
           <script src="vue-resource.js"></script>
           <script>
           window.onload=function(){
           new Vue({
           el:'body',
           data:{
           },
           methods:{
           get:function(){
           this.$http.jsonp('https://sug.so.360.cn/suggest',{
           word:'a'
           }).then(function(res){
           alert(res.data.s);
           },function(res){
           alert(res.status);
           });
           }
           }
           });
           };
           </script>
          </head>
          <body>
           <input type="button" value="按鈕" @click="get()">
          </body>
          </html>
          

          最后

          以下是總結出來最全前端框架視頻,包含: javascript/vue/react/angualrde/express/koa/webpack 等學習資料。

          【領取方式】

          關注頭條 前端全棧架構丶第一時間獲取最新前端資訊學習

          手機用戶可私信關鍵詞 【前端】即可獲取全棧工程師路線和學習資料!


          主站蜘蛛池模板: 亚洲国产情侣一区二区三区| 国产色综合一区二区三区| 国产主播福利一区二区| 亚洲av乱码一区二区三区| 日韩免费一区二区三区在线播放| 无码少妇A片一区二区三区| 日韩经典精品无码一区| 国精无码欧精品亚洲一区| 一区二区视频在线观看| 无码少妇一区二区三区芒果| 麻豆精品一区二区综合av| 亚洲一区无码中文字幕| 亚洲国产一区在线观看| 精品视频在线观看一区二区| 久久精品国产一区二区三区日韩| 国产主播在线一区| 国产另类ts人妖一区二区三区| 无码人妻久久一区二区三区| 精品人妻无码一区二区色欲产成人| 视频在线观看一区二区| 国产成人无码精品一区二区三区| 亚洲日韩国产一区二区三区在线| 亚洲性日韩精品一区二区三区| 精品无码人妻一区二区三区| 狠狠爱无码一区二区三区| 亚洲电影国产一区| 亚洲一区二区三区在线播放| 精品福利视频一区二区三区| 久久免费视频一区| 午夜一区二区在线观看| 无码日韩精品一区二区三区免费 | 香蕉一区二区三区观| 国产精品视频一区二区猎奇| 亚洲国产激情一区二区三区| 国产香蕉一区二区精品视频| 伊人色综合一区二区三区| 香蕉久久ac一区二区三区| 色窝窝无码一区二区三区| 亚洲日本一区二区一本一道| 精品国产一区二区三区久久影院| 亚洲AV无码一区二区三区系列|