AJAX
是异步向服务器请求数据,实现不刷新浏览器更新数据
组成
异步的JS
xhr对象
其他JS
服务器的数据
AJAX特点
提高了页面渲染速度
提高了用户体验
不需要插件支持
缺点
1.破坏了浏览器前进和后退机制(因为ajax自动更新机制
2.一个Ajax请求多了,也会出现页面加载慢的情况。
3.搜索引擎的支持程度比较低。
4.ajax的安全性问题不太好(可以用数据加密解决)。
AJAX的基本过程
使用ajax一共有4个步骤:1.创建ajax、2.连接服务器、3.发送请求、4.接受返回值。
HTTP请求
HTTP请求有两种方式
GET:用于获取数据,GET是在URL上传递数据(网址后面的东西),存储量较少,安全系数比较低。
POST:用于上传数据,POST安全性一般比(GET好一些),容量几乎是无限(多用于表单)。
AJAX GET请求 过程的简单封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="name">
<input type="text" id="age">
<input type="button" id="btn" value="提交">
<script>
var oa=document.getElementById('name')
var ob=document.getElementById('age')
var obtn=document.getElementById('btn')
obtn.onclick=function(){
ajaxGet("http://localhost/php/php-get.php",function(res){
alert(res)
},{
user:oa.value,
age:ob.value
})
}
function ajaxGet(url,fn,date){ //url 为 接口 fn 为执行方法 date 是发送的数据
date=date||{}
var str=""
for(var i in date){
str+=`${i}=${date[i]}&`
}
var d = new Date() //在url上拼接一个时间戳 避免浏览器缓存问题
url=url+"?"+str+"sjc"+d.getTime()
var xhr=new XMLHttpRequest();
xhr.open('get',url);
xhr.onreadystatechange=function(){
if(xhr.status==200&&xhr.readyState==4){
fn(xhr.responseText)
}else if(xhr.status!=200&&xhr.readyState==4){
fn(xhr.status)
}
xhr.send()
}
</script>
</body>
</html>
<?php
$u = @$_GET["user"];
$p = @$_GET["age"];
// $u = @$_POST["user"];
// $p = @$_POST["age"];
echo "收到的数据是:".$u."-----".$p
?>
AJAX POST请求 过程的简单封装
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="name">
<input type="text" id="age">
<input type="button" id="btn" value="提交">
<script>
var oa=document.getElementById('name')
var ob=document.getElementById('age')
var obtn=document.getElementById('btn')
obtn.onclick=function(){
ajaxPost("http://localhost/php/php-post.php",function(res){
alert(res)
},{
user:oa.value,
age:ob.value
})
}
function ajaxPost(url,fn,date){
date=date||{}
var str=""
for(var i in date){
str+=`${i}=${date[i]}&`
}
var d = new Date()
url=url+"?"+"sjc="+d.getTime()
console.log(url)
var xhr=new XMLHttpRequest();
xhr.open('post',url);
xhr.onreadystatechange=function(){
if(xhr.status==200 && xhr.readyState==4){
fn(xhr.responseText)
}else if(xhr.status!=200&&xhr.readyState==4){
fn(xhr.status)
}
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(str)
}
</script>
</body>
</html>
<?php
// $u = @$_GET["user"];
// $p = @$_GET["age"];
$u = @$_POST["user"];
$p = @$_POST["age"];
echo "收到的数据是:".$u."-----".$p
?>
AJAX GET 和 POST 二合一的封装
// 1.预设函数的执行方式,和要传入的参数,及要实现的功能
// ajax({
// type:"get", //可选,默认get
// url:"", //必选
// success:function(){}, //必选
// error:function(){}, //可选,默认不处理
// data:{} //可选,默认不发
// })
function ajax(options){
// 2.解析参数,处理默认参数
let {type,url,success,error,data} = options;
type = type || "get";
data = data || {};
// 3.解析要发送的数据
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
// 4.根据发送方式处理url
if(type == "get"){
var d = new Date();
url = url + "?" + str + "sjc=" + d.getTime();
}
// 5.开启ajax
var xhr = new XMLHttpRequest();
xhr.open(type,url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
success(xhr.responseText);
}else if(xhr.readyState == 4 && xhr.status != 200){
// 6.首先保证ajax的过程结束了,如果http给失败,才是真正的失败
error && error(xhr.status);
// if(error) error(xhr.status);
}
}
// 7.根据发送方式,决定发送的信息
if(type == "get"){
xhr.send()
}else if(type == "post"){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(str.slice(0,str.length-1));
}
}
AJAX GET/POST 和Jsonp三合一封装
// 1.预设函数的执行方式,和要传入的参数,及要实现的功能
// ajax({
// type:"get", //可选,默认get
// url:"", //必选
// success:function(){}, //必选
// error:function(){}, //可选,默认不处理
// data:{} //可选,默认不发
// timeout:毫秒数 //可选,默认500,延迟时间,超出时间就出错误,用在jsonp身上
// })
function ajax(options){
// 2.解析参数,处理默认参数
let {type,url,success,error,data,timeout} = options;
type = type || "get";
data = data || {};
timeout = timeout || 500;
// 3.解析要发送的数据
var str = "";
for(var i in data){
str += `${i}=${data[i]}&`;
}
// 4.根据发送方式处理url
// Jsonp1.处理url和数据
if(type == "get" || type == "jsonp"){
var d = new Date();
url = url + "?" + str + "sjc=" + d.getTime();
}
// Jsonp2.区分jsonp和ajax的功能
if(type === "jsonp"){
var script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
window[data[data.columnName]] = function(res){
success && success(res);
error = null;
}
// Jsonp3.jsonp的失败(超时)
setTimeout(() => {
error && error("timeout");
success = null;
}, timeout);
}else{
// 5.开启ajax
var xhr = new XMLHttpRequest();
xhr.open(type,url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
success(xhr.responseText);
}else if(xhr.readyState == 4 && xhr.status != 200){
// 6.ajax执行成功 但网络出错 才报错
error && error(xhr.status);
// if(error) error(xhr.status);
}
}
// 7.根据发送方式,决定发送的信息
if(type == "get"){
xhr.send()
}else if(type == "post"){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(str.slice(0,str.length-1));//去掉多余的&
}
}
}
AJAX GET/POST 和Jsonp三合一封装的调用
ajax({
type:"get", //可选,默认get
url:"", //必选
success:function(){}, //必选
error:function(){}, //可选,默认不处理
data:{} //可选,默认不发
timeout:毫秒数 //可选,默认500,延迟时间,超出时间,出错误,用在jsonp身上
})