Ajax——PHP基础语法、get/post请求处理、Ajax-GET和Ajax-POST的基本使用及封装、Ajax-jQuery、Ajax-XML、Ajax-JSON、Cookie、hash

1 篇文章 0 订阅

Ajax-服务器软件安装

  • Ajax用于网页和服务器交换数据。
1.基本概念
  • 什么是服务器?

    (1)服务器也是电脑,只不过是一台24小时不断电、不关机的电脑。

    (2)根据服务器提供的服务功能不同,可以分为:文件服务器、邮件服务器、web服务器等。

    (3)简单来说,服务器其实就是一台“提供了某种服务功能”的超级电脑。

  • 如何让电脑能够提供某种服务?

    如果想让电脑提供聊天服务,可以安装相应的聊天软件,如:QQ、微信等;如果想让电脑提供听歌服务,可以安装相应的音乐软件,如:网易云音乐、QQ音乐等。同理,想让电脑变成一台web服务器(提供管理网站的服务),只需要安装web服务相关的软件即可,比如:Apache、IIS、Tomcat、Nginx、NodeJS等。(安装了web服务软件等电脑就成为“Web服务器”)

2.Web服务器搭建
  • 可以安装某些综合性软件,使自己的电脑成为一台Web服务器,如:WAMPServer、XAMPP、phpStudy等。下面以安转WAMPPServer为例进行介绍。

(1)什么是WAMPServer?

W:Windows操作系统;

A:Apache(一种服务器软件,特点是简单、速度快、性能稳定);

M:MySQL(开源免费的数据库软件,特点是体积小、速度快、使用成本低);

P:PHP(超文本预处理器,直接将代码嵌入HTML文档中执行,特点是简单易学、容易上手)。

(2)如何搭建Web服务器?

① 双击提供的安装包

② 选择English,点击OK

③ 选择同意,点击Next

④ 点击Next

⑤ 选择安装路径(注意:路径中不要出现中文),然后一直点击Next继续安装

⑥ 点击install开始安装

⑦ 选择浏览器

⑧ 点击Next

⑨ 安装完毕以后点击finish即可启动WAMP

(3)测试访问

  • 打开浏览器输入127.0.0.1查看显示的内容,如果显示的内容出现了WampServer标志性的界面,就表示当前的电脑已经变成一台Web服务器。

PHP基础语法

  • PHP的基本结构:
<?php

?>
  • 注释:
单行注释:
//
多行注释:
/* */
  • 定义变量:
<?php
	$num = 10;		//变量名只能以数字、字母、下划线组成,并且不能以数字开头
?>
  • 打印内容:
<?php
	$num = 10;
	echo $num;		//通过echo,会把该值打印在网页中
	//后端编写的代码都不能直接运行,必须放到服务器对应的文件夹下,通过服务器运行
	//如何通过服务器运行:通过IP地址找到服务器对应的文件夹,然后再找到对应的文件运行
?>
  • 定义集合(数组、对象):
<?php
	//数组
	$arr = array(1,2,3);
	print_r($arr);		//echo不能打印集合(数组、对象),只能打印字符串等简单数组类型;而print_r则可以打印集合	
	echo "<br />";
	echo $arr[0];			//输出结果为:1

	//对象
	$obj = array("uname" => "andy","age" => "22");
	print_r($obj);
	echo "<br />";
	echo $obj["uname"];
?>
  • 分支循环语句:
<?php
	//if
	$age = 22;
	if($age >= 18){
    echo "成年人";
  }else{
    echo "未成年人";
  }

	//三元表达式
	$age = 22;
	$res = ($age >= 18) ? "成年人" : "未成年人";
	echo $res;

	//switch
	$day = 4;
	switch ($day) {
    case 0:
        echo = "星期天";
        break;
    case 1:
        echo = "星期一";
        break;
    case 2:
        echo = "星期二";
        break;
    case 3:
        echo = "星期三";
        break;
    case 4:
        echo = "星期四";
        break;
    case 5:
        echo = "星期五";
        break;
    default:
        echo = "星期六";
      	break;
	}

	//for
	$arr = array(1,2,3);
	for($i = 0;$i < count($arr); $i++){
    echo $arr[$i];
    echo "<br />";
  }

	//while
	$arr = array(1,2,3);
	$index = 0;
	while($index < count($arr)){
    echo $arr[$index];
    echo "<br />";
    $index++;
  }
?>

get、post请求处理

1.get请求处理
  • get请求会将提交的数据拼接到URL后面。

  • html页面相关代码:

<body>
  <form action="get.php" method="get">
    <input type="text" name="username"><br>
    <input type="password" name="userpwd"><br>
    <input type="submit" value="提交">
  </form>
</body>
  • PHP相关代码:
<?php
  	print_r($_GET);		//输出结果为:Array([username] => andy [userpwd] => 123)
	//$_GET可以获取由get发送的请求中携带的参数,是一个对象
	echo $_GET["usernmae"];	//输出结果为:andy
	echo $_GET["userpwd"];	//输出结果为:123
?>
  • 以上代码发送get请求的过程图如下:

在这里插入图片描述

2.post请求
  • post请求会将提交的数据放到请求头中。
  • html页面相关代码:
<body>
  <form action="post.php" method="post">
    <input type="text" name="username"><br>
    <input type="password" name="userpwd"><br>
    <input type="submit" value="提交">
  </form>
</body>
  • php相关代码:
<?php
  	print_r($_POST);		//输出结果为:Array([username] => andy,[userpwd] => 123)
	echo $_POSt['username'];		//输出结果为:andy
	echo $_POST["userpwd"];			//输出结果为:123
?>
3.get-post异同
  • 相同点:get和post都是将数据提交到远程服务器。

  • 不同点:

    (1)提交数据存储的位置不同。get请求会将数据放到URL后面(同时在浏览器的历史记录中,可以在URL网址后面查看到通过get请求提交的数据);而post请求会将数据放到请求头中(同时在浏览器的历史记录中,不能在URL网址后面查看到通过post请求提交的数据)。

    (2)提交数据大小限制不同。get请求对数据有大小限制,限制在不大于2000个字符;而post请求对数据没有大小限制。

  • get和post的应用场景:

    (1)get请求用于提交非敏感数据和小数据。

    (2)post请求用于提交敏感数据和大数据。

4.post文件上传
  • html页面相关代码:
<body>
  <form action="post-file.php",method="post" enctype="multipart/form-data">
    <input type="file" name="upFile"><br >
    <input type="submit" value="上传"><br >
  </form>
</body>
  • PHP相关代码:
<?php
  	print_r($_POST);		//输出结果为:Array([upFile] => bg.jpg)
	//如果html结构的form加了enctype属性,那么输出结果则为:Array()
	print_r($_FILES);		//输出结果为:Array([upFile => Array([name] => bg.jpg) [type] => image/jpeg] [tmp_name] => D:\wamp64\tmp\phpB45A.tmp [error] => 0 [size] => 438201),其中,tmp_name是存放的临时路径
	//如果html结构的form没有加enctype属性,那么输出结果为:Array()

	//把上传的文件保存起来
	//1.获取上传文件对应的字典
	$fileInfo = $_FILES["upFile"];
	//2.获取上传文件的名称
	$fileName = $_FILES["name"];
	//3.获取上传文件保存的临时路径
	$filePath = $_FILES["tmp_name"];
	//4.移动文件
	move_uploaded_file($filePath,"./img/".$fileName);
?>
  • move_uploaded_file(file,newloc):
参数描述
file必需。规定要移动的文件。
newloc必需。规定文件的新位置。

注意:
(1)上传文件一般使用POST提交
(2)上传文件必需设置enctype=“multipart/form-data”
(3)上传的文件在PHP中可以通过FILES获取
(4)PHP中文件默认会上传到一个临时目录,接收完毕之后会自动删除

5.post-大文件上传
  • 默认情况下,服务器对上传文件的大小是有限制的,如果想修改上传文件的限制,可以修改php.ini文件。(该文件一般是位于:wamp安装目录下的bin/apache/apachex.x.xx/bin)
file_uploads = On;		是否允许上传文件,On/Off,默认是On
upload_max_filesize = 2048M;			上传文件的最大限制
post_max_size = 2048M;						通过Post提交的最多数据
max_execution_time = 30000;				脚本最长的执行时间,单位为秒
max_input_time = 30000;						接收提交的数据的时间限制,单位为秒
memory_limit = 2048M;							最大的内存消耗

Ajax-GET

1.Ajax-GET基本使用
  • 什么是Ajax?

    Ajax是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

  • 如何使用Ajax:

html页面相关代码:

<head>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
        //1.创建一个异步对象
        var xmlhttp = new XMLHttpRequest();
        //2.设置请求方式和请求地址
        xmlhttp.open("GET","ajax-get.php",true);
        //3.发送请求
        xmlhttp.send();
        //4.监听状态的变化
        xmlhttp.onreadystatechange = function(e2){
          if(xmlhttp.readyState === 4){
            //判断请求是否成功
            if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
              //5.处理返回到结果
              console.log("接收到服务器返回到数据");
            }else{
              console.log("没有接收到服务器返回到数据");
            }
          }
        }
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>

PHP相关代码(ajax-get.php):

<?php
  echo "Ajax get page!";
?>
  • xmlhttp.open(method , url , async)
参数说明
method请求的类型:GET或POST
url文件在服务器上的位置
asynctrue(异步)或false(同步)
  • XMLHttpRequest对象的三个重要参数:
属性说明
onreadystatechange存储函数(或函数名),每当readyState属性改变时,就会调用该函数
readyState存有XMLHttpRequest的状态。从0到4发生变化。
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪(只是代表请求完成,不代表请求成功,有可能是成功也有可能失败)
status200:"OK"
404:为找到页面
2.Ajax-GET-IE兼容
  • 服务器响应

    如需获得来自服务器的响应,请使用XMLHttpRequest对象的responseText或responseXML属性。

    属性说明
    responseText获得字符串形式的响应数据
    responseXML获得XML形式的响应数据
  • 所有现代浏览器均支持XMLHttpRequest对象(IE5和IE6使用ActiveXObject),其兼容性写法如下:

var xmlhttp;
if(window.XMLHttpRequest){
  xmlhttp = new XMLHttpRequest();
}else{
  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
  • 问题1及其解决办法:
<head>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
        //var xmlhttp = new XMLHttpRequest();
        //兼容性写法(问题1:IE5、IE6不兼容)
        var xmlhttp;
        if(window.XMLHttpRequest){
          xmlhttp = new XMLHttpRequest();
        }else{
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","ajax-get.php",true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function(e2){
          if(xmlhttp.readyState === 4){
            if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
              alert(xmlhttp.responseText);		//弹出结果为:Ajax get page!
            }else{
              alert("请求失败");
            }
          }
        }
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-get.php相关代码
<?php
  echo "Ajax get page!";
?>
  • 问题2及其解决办法:
<head>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
        //var xmlhttp = new XMLHttpRequest();
        //兼容性写法(问题1:IE5、IE6不兼容)
        var xmlhttp;
        if(window.XMLHttpRequest){
          xmlhttp = new XMLHttpRequest();
        }else{
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //问题2:在IE浏览器中,如果通过Ajax发送GET请求,那么IE浏览器会认为同一个URL只有一个结果
        //解决方法:让每次访问的URL地址都不一样,可以通过下面两种方式:
        //Math.randon();
        //new Date().getTime()
        xmlhttp.open("GET","ajax-get.txt?t="+(new Date().getTime()),true);
        xmlhttp.send();
        xmlhttp.onreadystatechange = function(e2){
          if(xmlhttp.readyState === 4){
            if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
              alert(xmlhttp.responseText);		//弹出结果为:abc
            }else{
              alert("请求失败");
            }
          }
        }
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-get.txt
abc 
3.Ajax-GET封装
//myAjax.js
function obj2str(obj){
  obj.t = new Date().getTime();
  var res = [];
  for(var key in obj){
    //encodeURIComponent()方法可把字符串作为 URI 组件进行编码。
    //发送GET请求时,URL中不能出现中文,所以可以使用encodeURIComponent()方法进行转码。
    //URL中只可以出现字母/数字/下划线/ASCII码,其他都需要encodeURIComponent()方法进行转码。
    res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
  }
  return res.join("&");		//userName=andy&userPwd=123
}
function ajax(url,obj,timeout,success,error){
  //0.将对象转换为字符串
  var str = obj2str(obj);
  //1.创建一个异步对象
  //var xmlhttp = new XMLHttpRequest();
  var xmlhttp,timer;
  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  //2.设置请求方式和请求地址
  //xmlhttp.open("GET",url+"?t="+(new Date().getTime()),true);
  xmlhttp.open("GET",url+"?"+str,true);
  //3.发送请求
  xmlhttp.send();
  //4.监听状态的变化
  xmlhttp.onreadystatechange = function(e2){
    if(xmlhttp.readyState === 4){
      clearInterval(timer);		//此时已经接收到服务器响应,所以此时关闭定时器比较严谨
      //判断请求是否成功
      if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
        //5.处理返回到结果
        success(xmlhttp);
      }else{
        error(xmlhttp);
      }
    }
  }
  //判断外界是否传入了超时时间
  if(timeout){
    timer = setInterval(function(){
      console.log("中断请求")	;
      xmlhttp.abort();		//中断请求
      clearInterval(timer);
    },timeout);
  }
}
//ajax-get.html
<head>
  <script src="myAjax.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       ajax("ajax-get.php",{
         "userName":"andy",
         "userPwd":"123"
       },3000
       ,function(xhr){
         alert(xhr.responseText);
       },function(xhr){
         alert("请求失败");
       });
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-get.php
<?php
  //sleep(5);			//执行到这里会停留5秒钟,5秒钟之后才执行后面代码,也就是,5秒之后才返回响应结果
  echo $_GET["userName"];
	echo $_GET["userPwd"];
?>

Ajax-POST

1.Ajax-POST基本使用
<head>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
        var xmlhttp;
        if(window.XMLHttpRequest){
          xmlhttp = new XMLHttpRequest();
        }else{
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("POST","ajax-post.php",true);
        //注意点:以下这行代码必须放到open和send之间
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("userName=andy&userPwd=123");
        xmlhttp.onreadystatechange = function(e2){
          if(xmlhttp.readyState === 4){
            if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
              alert(xmlhttp.responseText);		//弹出结果为:Ajax post page!(还没有传递参数时的输出结果)
              //弹出结果为:andy123(传递参数时的输出结果)
            }else{
              alert("请求失败");
            }
          }
        }
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-post.php
<?php
  //echo "Ajax post page!";
  echo $_POST["userName"];
  echo $_POST["userPwd"];
?>
2.Ajax-POST封装
//myAjax2.js
function obj2str(obj){
  obj.t = new Date().getTime();
  var res = [];
  for(var key in obj){
    //encodeURIComponent()方法可把字符串作为 URI 组件进行编码。
    //发送GET请求时,URL中不能出现中文,所以可以使用encodeURIComponent()方法进行转码。
    //URL中只可以出现字母/数字/下划线/ASCII码,其他都需要encodeURIComponent()方法进行转码。
    res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key]));
  }
  return res.join("&");		//userName=andy&userPwd=123
}
function ajax(type,url,obj,timeout,success,error){
  //0.将对象转换为字符串
  var str = obj2str(obj);
  //1.创建一个异步对象
  //var xmlhttp = new XMLHttpRequest();
  var xmlhttp,timer;
  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  //2.设置请求方式和请求地址
  //xmlhttp.open("GET",url+"?t="+(new Date().getTime()),true);
  if(type === "GET"){
    xmlhttp.open(type,url+"?"+str,true);
  }else{
    xmlhttp.open(type,url,true);
    //注意点:以下这行代码必须放到open和send之间
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(str);
  }
  
  //3.发送请求
  xmlhttp.send();
  //4.监听状态的变化
  xmlhttp.onreadystatechange = function(e2){
    if(xmlhttp.readyState === 4){
      clearInterval(timer);		//此时已经接收到服务器响应,所以此时关闭定时器比较严谨
      //判断请求是否成功
      if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
        //5.处理返回到结果
        success(xmlhttp);
      }else{
        error(xmlhttp);
      }
    }
  }
  //判断外界是否传入了超时时间
  if(timeout){
    timer = setInterval(function(){
      console.log("中断请求")	;
      xmlhttp.abort();		//中断请求
      clearInterval(timer);
    },timeout);
  }
}
//ajax-post.html
<head>
  <script src="myAjax2.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       ajax("POST","ajax-post.php",{
         "userName":"andy",
         "userPwd":"123"
       },3000
       ,function(xhr){
         alert(xhr.responseText);
       },function(xhr){
         alert("请求失败");
       });
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-post.php
<?php
  //echo "Ajax post page!";
  echo $_POST["userName"];
  echo $_POST["userPwd"];
?>

Ajax-jQuery封装

//ajax-jquery.html
<head>
  <script src="js/jquery-1.12.4.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       $.ajax({
         type:"GET",		//优势1:大小写都可以,即GET或get都能发送请求
         url:"ajax-jquery.php",
         data:"userName=andy&userPwd=123",
         success: function(msg){
           alert(msg);		//弹出的结果为:andy123
         },
         error: function(xhr){
           alert(xhr.status);
         }
       });
        //优势2:以对象的形式传递参数,不用考虑属性及方法的顺序
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-jquery.php
<?php
  echo $_POST["userName"];
  echo $_POST["userPwd"];
?>

借鉴jQuery中的Ajax,封装自己的Ajax

//myAjax3.js
function obj2str(data){
  data.t = new Date().getTime();
  var res = [];
  for(var key in data){
    //encodeURIComponent()方法可把字符串作为 URI 组件进行编码。
    //发送GET请求时,URL中不能出现中文,所以可以使用encodeURIComponent()方法进行转码。
    //URL中只可以出现字母/数字/下划线/ASCII码,其他都需要encodeURIComponent()方法进行转码。
    res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key]));
  }
  return res.join("&");		//userName=andy&userPwd=123
}
//function ajax(type,url,obj,timeout,success,error){
function ajax(option){	//借鉴jQuery中的Ajax的第二点(以对象形式传递参数)
  //0.将对象转换为字符串
  var str = obj2str(option.data);
  //1.创建一个异步对象
  //var xmlhttp = new XMLHttpRequest();
  var xmlhttp,timer;
  if(window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
  }else{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  //2.设置请求方式和请求地址
  //xmlhttp.open("GET",url+"?t="+(new Date().getTime()),true);
  if(option.type.toLowerCase() === "get"){		//借鉴jQuery中的Ajax的第一点(把请求方式转换为小写)
    xmlhttp.open(option.type,option.url+"?"+str,true);
  }else{
    xmlhttp.open(option.type,option.url,true);
    //注意点:以下这行代码必须放到open和send之间
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(str);
  }
  
  //3.发送请求
  xmlhttp.send();
  //4.监听状态的变化
  xmlhttp.onreadystatechange = function(e2){
    if(xmlhttp.readyState === 4){
      clearInterval(timer);		//此时已经接收到服务器响应,所以此时关闭定时器比较严谨
      //判断请求是否成功
      if(xmlhttp.status >= 200 && xmlhttp < 300 || xmlhttp.status === 304){
        //5.处理返回到结果
        option.success(xmlhttp);
      }else{
        option.error(xmlhttp);
      }
    }
  }
  //判断外界是否传入了超时时间
  if(option.timeout){
    timer = setInterval(function(){
      console.log("中断请求")	;
      xmlhttp.abort();		//中断请求
      clearInterval(timer);
    },option.timeout);
  }
}
//ajax.html
<head>
  <script src="myAjax3.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       ajax({
         url:"ajax.php",
         data:{
           "userName":"andy",
           "userPwd":"123"
         },
         type:"GET",
         timeout:3000,
         success:function(xhr){
           alert(xhr.responseText);
         },
         error:dunction(xhr){
         alert("请求失败!");
       }
       })
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax.php
<?php
  echo $_POST["userName"];
  echo $_POST["userPwd"];
?>

Ajax-XML

  • XML是一种可扩展标记语言。
//info.xml
<?xml version="1.0" encoding="UTF-8" ?>
<person>		//根标签,类似html中的<html></html>标签,不过它是可以随便命名的
		<name>andy</name>
  	<age>22</age>
</person>
//ajax.html
<head>
  <script src="myAjax3.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       ajax({
         type:"get"
         url:"ajax-xml.php",
         success:function(xhr){
           //console.log(xhr.respnseXML);
         	 var res = xhr.responseXML;
         	 //console.log(res.querySelector("name"));输出结果为:<name>andy</name>
         	 console.log(res.querySelector("name").innerHTML);		//输出结果为:andy
         	 console.log(res.querySelector("age").innerHTML);			//输出结果为:22
         },
         	error:dunction(xhr){
         	 console.log(xhr.status);
       }
       })
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>
//ajax-xml.php
//执行结果中有中文,必须在php文件顶部设置
//header("content-type:text/html;chartset=utf-8");
//如果PHP中需要返回XML数据,也必须在PHP文件顶部设置
header("content-type:text/xml;chartset=utf-8");		//如果没有这行代码,那么前端打印的结果就为:null;如果有,则返回#document,该document和js中的document类似,js中获取元素的方法,这里都可以使用,比如:querySelector等
echo file_get_contents("info.xml");

Ajax-JSON

  • JSON是JS对象的字符串表示法,它使用文本表示一个JS对象的信息,本质是一个字符串。

    var obj = {a:'Hello', b:'World'};		//这是一个对象,注意键名也是可以使用引号包裹的
    var json = '{"a":"Hello", "b":"World"}';	//这是一个JSON字符串,本质是一个字符串
    
  • JSON和JS对象互转:

    1.对象转换为JSON字符串,使用JSON.stringify()方法:

    var json = JSON.stringify({a:'Hello', b:'World'});	//输出结果是:'{"a":"Hello", "b":"World"}'
    

    2.JSON转换为对象,使用JSON.parse()方法:

    var obj = JSON.parse('{"a":"Hello", "b":"World"}');		//输出结果为:{a:'Hello', b:'World'}
    
  • JSON的参数名必须加双引号;而参数值如果是字符串,也必须加双引号,是数字类型就不用加双引号。

  • 实操:

//ajax-json.txt
{
		"name":"andy",
		"age":"22"
}
//ajax-json.php
<?php
  echo file_get_contents("ajax.json.txt");
?>
//ajax.html
<head>
  <script src="myAjax3.js"></script>
  <script>
  	window.onload = function(e){
      var oBtn = document.querySelector("button");
      oBtn.onclick = function(e1){
       ajax({
         type:"get"
         url:"ajax-json.php",
         success:function(xhr){
           //console.log(xhr.responseText);
         	 var str = xhr.responseText;
         	 var obj = JSON.parse(str);		//JSON.parse()在IE8及以下的版本是不支持的,如果想在IE8及以下的版本使用该方法,则需要使用json2.js这个框架。使用步骤:1.到GitHub上下载相关的json2.js,然后导入到项目中,并引入到需要使用到文件中即可。2.使用方法和原生的JSON.parse()方法和JSON.stringify()方法的使用一样。
         	 console.log(obj.name);
         	 console.log(obj.age);
         },
         	error:dunction(xhr){
         	 console.log(xhr.status);
       }
       })
      }
    }
  </script>
</head>
<body>
  <button>
    	发送请求
  </button>
</body>



  • JSON比XML体积小,所以JSON传输速度更快,用户体验更好。

Cookie

1.Cookie基本使用
<head>
  <script>
  	window.onload = funciton(e){
      /*
      cookie:会话跟踪技术(客户端)
      session:会话跟踪技术(服务端)
      
      cookie的作用:将网页中的数据保存到浏览器中
      
      cookie的生命周期:
      默认情况下,cookie的生命周期是一次会话(浏览器被关闭,就代表一次会话结束);
      如果通过expires=设置了过期时间,并且过期时间没有过期,那么下次打开浏览器,cookie中的数据还是存在的;
      如果通过expires=设置了过期时间,并且已经过期了,那么会立即删除保存的数据。
      
      cookie的注意点:
      1.cookie默认不会保存任何的数据
      2.cookie不能一次性设置多条数据,要想保存多条数据,只能一条一条的设置
      3.cookie有大小和个数的限制:
      个数限制:20~50个,为了兼容所有的浏览器,一般不会超过20个
      大小限制:4KB左右
      
      cookie的作用范围:同一个浏览器的同一个路径下访问(比如:127.0.0.1/jQuery/Ajax/cookie.html和127.0.0.1/jQuery/Ajax/cookie-test.html是同一个路径,都能访问保存在cookie中的数据)
      如果说保存到了/jQuery/Ajax路径下,我们如何才能在/jQuery/Ajax/cookie/和/jQuery/下都能访问cookie中的数据:
      如果在同一个浏览器中,默认情况,下一级路径是可以访问的。(如:/jQuery/Ajax/cookie/cookie.html)
      如果在同一个浏览器中,想让上一级目录也能访问保存的cookie,那么需要添加一个path属性才可以:
      docuemnt.cookie = "name=andy;path=/;";
      
      如果在www.bin.com下保存了一个cookie,那么在edu.bin.com中是无法访问的。想要在edu.bin.com中也能访问,那么需要添加一句代码:domain=bin.com。(其中,bin.com是根域名,而www和edu都是二级域名)
      docuemnt.cookie = "name=andy;path=/;domain=bin.com;";
      */
      //alert(document.cookie);		//没有结果,一片空白
      
      //document.cookie = "age=22;";	//设置cookie中的数据
      //alter(document.cookie);			//获取cookie中的数据
      
      var date = new Date();
      date.setDate(date.getDate() + 1);
      document.cookie = "age=22;expires="+date.toGMTString+";";	//设置cookie的过期时间
      
      document.cookie = "name=andy;";
      document.cookie = "age=22;";
      alert(document.cookie);		//弹出结果为:name=andy;age=22
      document.cookie = "name=andy;age=22;gender=male;";		//只保存了name=andy,其它不保存
    }
  </script>
</head>
2.Cookie方法的封装
//cookie-封装.html
<head>
  <script>
  	window.onload = function(e){
      //添加cookie
      function addCookie(key,value,day,path,domain){
        //1.处理默认保存的路径
        var index = window.location.pathname.lastIndexOf("/");
        var currentPath = window.location.pathname.slice(0,index);
        path = path || currentPath;
        //2.处理默认保存的domain
        domain = domain || document.domain;
        //3.处理默认的过期时间
        if(!day){
          document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
        }else{
          var date = new Date();
          date.setDate(date.getDate() + day);
          document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
        }
      }
      addCookie("name","andy",1,"/","127.0.01");
      
      //获取cookie
      function getCookie(key){
        var res = document.cookie.split(";");
        for(var i = 0;i < res.length; i++){
          var temp = res[i].split("=");
          if(temp[0].trim() === key){
            return temp[1];
          }
        }
      }
      console.log(getCookie("name"));
      //删除cookie
      //默认情况下(没有path形参),只能删除默认路径中保存的cookie,如果想要删除指定路径中保存的cookie,那么必须在删除的时候指定路径才可以(即传入path)。
     function delCookie(key,path){
       addCookie(key,getCookie(key),-1,path);
     } 
      delCookie("name","/");
    }
  </script>
</head>
  • 把以上三个方法封装成一个jQuery插件的方法:
//jquery-cookie.js(封装成jQuery插件的文件命名有一定的格式:jquery+功能/作用.js)
;(function($,window){
  $.extend({
    addCookie:function (key,value,day,path,domain){
        //1.处理默认保存的路径
        var index = window.location.pathname.lastIndexOf("/");
        var currentPath = window.location.pathname.slice(0,index);
        path = path || currentPath;
        //2.处理默认保存的domain
        domain = domain || document.domain;
        //3.处理默认的过期时间
        if(!day){
          document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
        }else{
          var date = new Date();
          date.setDate(date.getDate() + day);
          document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
        }
      },
    getCookie:function (key){
        var res = document.cookie.split(";");
        for(var i = 0;i < res.length; i++){
          var temp = res[i].split("=");
          if(temp[0].trim() === key){
            return temp[1];
          }
        }
      },
    delCookie:function (key,path){
       addCookie(key,getCookie(key),-1,path);
     }
  })
})(jQuery,window)
  • 弊端:只能在本地使用,换一个浏览器或者发给别人,别人通过你发送的地址打开,打开的都是该网站的第一页。

hash

  • hash就是在URL地址后面加上#1或者#2…。
  • 优势:复制URL地址后,无论是换一个浏览器打开或者发给别人,别人通过你发送的地址打开,打开的都是你复制前打开的那一页的内容。
<head>
  <script>
  	//添加hash
    window.location.hash = 2;	//通过这行代码,就可以在URL地址后面添加hash,如:127.0.0.1/jQuery/Ajax/hash.html#2
    console.log(window.location.hash);		//输出结果为:#2
    console.log(window.location.hash.substring(1));		//输出结果为:2
  </script>
</head>
  • 一般情况下,在企业中,记录页码更多使用的hash,而不是cookie。

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值