整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

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 href="http://www.865171.cn"><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 等学习资料。

【领取方式】

关注头条 前端全栈架构丶第一时间获取最新前端资讯学习

手机用户可私信关键词 【前端】即可获取全栈工程师路线和学习资料!