GET基本使用
什么是Ajax?
AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。
使用Ajax的五部曲:
1.创建一个异步对象
let xmlhttp=new XMLHttpRequest();
2.设置请求方式和请求地址
格式:xmlhttp.open(method,url,async);
method:请求的类型;GET 或 POST
url:文件在服务器上的位置
async:true(异步)或 false(同步), Ajax存在的意义就是true
3.发送请求
xmlhttp.send();
4.监听状态的变化
xmlhttp.onreadystatechange = function (ev){};
onreadystatechange的五种状态
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
5.处理返回的结果
发送请求
window.onload = function (ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev1) {
// 1.创建一个异步对象
var xmlhttp=new XMLHttpRequest();
// 2.设置请求方式和请求地址
xmlhttp.open("GET", "04-ajax-get.php", true);
// 3.发送请求
xmlhttp.send();
// 4.监听状态的变化
xmlhttp.onreadystatechange = function (ev) {
if(xmlhttp.readyState === 4){ // 判断是否请求成功
if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
xmlhttp.status === 304){ // 判断是否接受到服务器返回的数据
// 5.处理返回的结果
console.log("接收到服务器返回的数据");
}else{
console.log("没有接收到服务器返回的数据");
}
}
}
}
}
GET-IE兼容
GET在IE浏览器存在的两个问题
1.兼容问题:创建对象时,XMLHttpRequest大部分浏览器都支持,只有IE5和IE6不支持(需要用ActiveXObject)
2.返回数据不更新问题:如果通过Ajax发送GET请求,那么IE浏览器认为同一个URL只有一个结果,也就是只会返回最初的结果
问题1的兼容问题处理方法:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
问题2的返回数据不更新问题处理方法:
在设置请求地址的后面添加随机的数值,使得每次发送请求的地址都不相同
随机数值方法1——获取随机0-1的数值:Math.random();
随机数值方法2——获取当前时间:new Date().getTime();
xmlhttp.open("GET","05-ajax-get.txt?t="+(new Date().getTime()),true);
Ajax——GET封装
window.onload = function () {
let btn = document.querySelector('button');
btn.onclick = function (ev) {
ajax('try.php', {
'userName': 'lnj',
'userPwd': '123456'
}, 3000, function (xhr) {
alert(xhr.responseText);
},function (xhr) {
alert('请求失败');
});
};
}
发送请求
echo $_GET['userName'];
echo '
';
echo $_GET['userPwd'];
?>
在URL中是不可以出现中文的,如果出现了中文需要转码,可以调用encodeURIComponent方法
URL中只可以出现字母/数字/下划线/ASCII码
function obj2str(obj) {
obj = obj || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
obj.t = new Date().getTime();
let res = [];
for(let key in obj){
res.push(encodeURIComponent(key)+'='+encodeURIComponent(obj[key]));
}
return res.join('&');
}
function ajax(url, obj, timeout, success, error){
// 0.对象转换为字符串
let str = obj2str(obj);
// 1.创建一个异步
let xmlhttp, timer;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求方式和请求地址
xmlhttp.open('GET', url+'?'+str,true);
// 3.发送请求
xmlhttp.send();
// 4.监听状态的变化
xmlhttp.onreadystatechange = function (ev) {
if(xmlhttp.readyState === 4){
clearInterval(timer);
if(xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304){
// 5.返回处理结果
success(xmlhttp);
}else{
error(xmlhttp);
}
}
}
if(timeout){
timer = setInterval(function () {
console.log('超时');
xmlhttp.abort();
clearInterval(timer);
},timeout);
}
}
POST基本使用
POST和GET的区别
1.以下代码必须放到open和send之间,用setRequestHeader来添加HTTP头
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
2.send()括号里需要写明格式
xmlhttp.send("userName=zs&userPwd=321");
3.路径后面不同
POST封装
window.onload = function () {
let btn = document.querySelector('button');
btn.onclick = function (ev) {
ajax('try.php', {
'userName': 'lnj',
'userPwd': '123456'
}, 3000, function (xhr) {
alert(xhr.responseText);
},function (xhr) {
alert('请求失败');
});
};
}
发送请求
echo $_POST['userName'];
echo '
';
echo $_POST['userPwd'];
?>
在URL中是不可以出现中文的,如果出现了中文需要转码,可以调用encodeURIComponent方法
URL中只可以出现字母/数字/下划线/ASCII码
function obj2str(obj) {
obj = obj || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
obj.t = new Date().getTime();
let res = [];
for(let key in obj){
res.push(encodeURIComponent(key)+'='+encodeURIComponent(obj[key]));
}
return res.join('&');
}
function ajax(url, obj, timeout, success, error){
// 0.对象转换为字符串
let str = obj2str(obj);
// 1.创建一个异步
let xmlhttp, timer;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求方式和请求地址
xmlhttp.open('POST', url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 3.发送请求
xmlhttp.send(str);
// 4.监听状态的变化
xmlhttp.onreadystatechange = function (ev) {
if(xmlhttp.readyState === 4){
clearInterval(timer);
if(xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304){
// 5.返回处理结果
success(xmlhttp);
}else{
error(xmlhttp.status);
}
}
}
if(timeout){
timer = setInterval(function () {
console.log('超时');
xmlhttp.abort();
clearInterval(timer);
},timeout);
}
}
Ajax-jQuery封装
window.onload = function () {
let btn = document.querySelector('button');
btn.onclick = function (ev) {
ajax({
url:'try.php',
data:{
'userName': 'lnj',
'userPwd': '123456'
},
timeout: 3000,
type: 'post',
success: function (xhr) {
alert(xhr.responseText);
},
error: function (xhr) {
alert('请求失败');
}});
};
}
发送请求
function obj2str(data) {
data = data || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
data.t = new Date().getTime();
let res = [];
for(let key in data){
res.push(encodeURIComponent(key)+'='+encodeURIComponent(data[key]));
}
return res.join('&');
}
function ajax(option){
// 0.对象转换为字符串
let str = obj2str(option.data);
// 1.创建一个异步
let xmlhttp, timer;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求方式和请求地址
if(option.type.toLowerCase() === "get"){
xmlhttp.open(option.type, option.url+'?'+str,true);
// 3.发送请求
xmlhttp.send();
}else{
xmlhttp.open(option.type, option.url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 3.发送请求
xmlhttp.send(str);
}
// 4.监听状态的变化
xmlhttp.onreadystatechange = function (ev) {
if(xmlhttp.readyState === 4){
clearInterval(timer);
if(xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status === 304){
// 5.返回处理结果
option.success(xmlhttp);
}else{
option.error(xmlhttp.status);
}
}
}
if(option.timeout){
timer = setInterval(function () {
console.log('超时');
xmlhttp.abort();
clearInterval(timer);
}, option.timeout);
}
}
XML
XML文件跟html很相似
XML前面必须写上<?xml version="1.0" encoding="UTF-8" ?>
后面必须有一个根节点,也就是随便写一对自定义标签
然后在根节点里添加你想添加的内容即可
示例:
李南江
33
PHP文件中执行结果中有中文,必须在php文件顶部设置:header("content-type:text/html;charset=utf-8");
如果PHP中需要返回XML数据,也必须在PHP文件顶部设置:echo file_get_contents("XXX.xml");
示例:
header("content-type:text/xml; charset=utf-8");
echo file_get_contents("XXX.xml"); //可以把xml数据返回给前端
JSON
JSON和JS对象互转
JSON字符串转化为JS对象
高版本浏览器使用JSON.parse()方法
在低版本的IE中,不可以使用原生的JSON.parse方法, 但是可以使用json2.js这个框架来兼容
==建议用eval("("+obj+")")来转化==,这个方法无论是否是标准的JSON都可以转化为JS对象
let obj = JSON.parse('{"a": "Hello", "b": "World"}'); //结果是 {a: 'Hello', b: 'World'}
注意点:
JSON文件内容:
{error: 0, id: 新添加内容的ID, time: 添加时间, acc: 点赞数, ref: 点踩数}
返回的非标准的JSON字符串: {error: 0, id: 1, time: 1526541587, acc: 0, ref: 0}
标准的JSON字符串应该是: {"error": "0", "id": "1", "time": "1526541587", "acc": "0", "ref": "0"}
非标准JSON字符串,若是用JSON.parse()方法转化的话,控制台会报错如下
VM179:1 Uncaught SyntaxError: Unexpected token e in JSON at position 1
JS对象转化为JSON字符串,使用JSON.stringify()方法
let json = JSON.stringify({a: 'Hello', b: 'World'}); //结果是 '{"a": "Hello", "b": "World"}'
示例:
window.onload = function (ev) {
var oBtn = document.querySelector("button");
oBtn.onclick = function (ev) {
ajax({
type:"get",
url:"XXX.php",
success: function (xhr) {
var str = xhr.responseText; //JSON是个txt文件
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);
},
error: function (xhr) {
console.log(xhr.status);
}
})
}
}
发送请求
JSON文件:
{
"name":"lnj",
"age":"33"
}
PHP文件里直接写file_get_contents,把JSON文件传入即可
echo file_get_contents("XXX.txt");
==XML和JSON的选择==:
在企业中,我们选择JSON,因为JSON的体积比XML小一些,传输快,用户体验好
cookie
会话跟踪技术有两种
cookie 客户端
session 服务端
cookie作用:
将网页中的数据保存到浏览器中
cookie生命周期:
默认情况下生命周期是一次会话(浏览器被关闭)
如果通过expires=设置了过期时间,并且过期时间没有过期, 那么下次打开浏览器还是存在
如果通过expires=设置了过期时间,并且过期时间已经过期了,那么会立即删除保存的数据
var date = new Date();
date.setDate(date.getDate() - 1); // 今天日期减一天
document.cookie = "age=33;expires="+date.toGMTString()+";";
alert(document.cookie);
cookie注意点:
cookie默认不会保存任何的数据
cookie不能一次性保存多条数据,要想保存多条数据,只能一条一条的设置
cookie有大小和个数的限制(浏览器不同,限制的不同)
个数限制: 20~50
大小限制: 4KB左右
document.cookie = "name=lnj;";
document.cookie = "age=33;";
alert(document.cookie);
// document.cookie = "name=lnj;age=33;gender=male;"; //这是错误写法,只能显示出设置的第一条
cookie作用范围:
同一个浏览器的同一个路径下访问
同一个文件夹内不同文件也是算的
如果在同一个浏览器中,默认情况下下一级路径就可以访问
如果在同一个浏览器中,想让上一级目录也能访问保存的cookie,那么需要添加一个path属性才可以document.cookie = "path=/;"; /代表根目录
域名也是有讲究的,若二级域名不同,也想访问的话,需要添加domain属性,设置domain=根域名
示例1:
保存到了www.it666.com/jQuery/Ajax/路径下,我们想在 www.it666.com/jQuery/Ajax/13-weibo/,和 www.it666.com/jQuery/ 路径下也能访问
document.cookie = "name=zs;path=/;";
示例2:
我们在www.it666.com下面保存了一个cookie,那么我们在edu.it666.com中是无法访问的
如果想在edu.it666.com中也能访问,那么我们需要再添加一个domain属性才可以;
document.cookie = "name=zs;path=/;domain=it666.com;";
alert(document.cookie);
cookie添加方法封装
function addCookie(key, value, day, path, domain) {
// 1.设置默认路径
let index = window.location.pathname.lastIndexOf('/');
let 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 {
let date = new Date();
date.setDate(date.getDate() + day);
document.cookie = key+"="+value+";domain="+domain+";path="+path+";expires="+date.toGMTString()+";";
}
}
cookie获取和删除方法封装
默认情况下只能删除默认路径中保存的cookie,如果想删除指定路径保存的cookie,那么必须在删除的时候指定路径才可以
function getCookie(key) {
let res = document.cookie.split(';');
for (let i = 0; i < res.length; i++){
let temp = res[i].split('=');
if(temp[0].trim() === key){
return temp[1];
}
}
}
// console.log(getCookie('dat'));
function delCookie(key,path) {
addCookie(key,getCookie(key),-1,path);
}
// delCookie('score','/');
hash
设置
window.location.hash = 值;
window.location.hash = 3;
获取
window.location.hash.substring(1);
console.log(window.location.hash.substring(1));
// 截取索引为1以后的hash值,其实就是返回#号后面的值
相对于cookie的好处就是,同一个路径,不同地方打开时依旧还是当初看的那一页;分享给别人时,你看的是哪页,对方看到的就是哪一页