这篇博客用来总结Ajax,包括了挺多新的知识。
一、Ajax基本信息
Ajax被用在前后端分离开发,连接在数据接口(api)上,它运用了异步请求的方法(请求和后续代码同时执行)。所以总结来说,Ajax是专门做后台数据的访问的。
首先学习原生js的ajax,面向的是XMLhttprequest对象,也是后台数据访问的对象。原生js用Ajax访问后台数据一般分为5个步骤:
1.实例化对象
2.open 连接远程服务器
参数:
method:请求的方式
get post
url:请求的服器路径,
async :当前的请求是同步还是异步 true 异步 false 同步
user 用户名
password 密码
3. send() 发送请求
4.响应事件onreadystatechange
5.渲染界面
1.创建对象
/*var http = new XMLHttpRequest();
2.建立服务器连接
http.open(“get”, “./data/student.txt”);
3.发送请求
http.send();
4.服务器响应
http.onreadystatechange = function () {}
5.界面的渲染
判断 获取最终读取完成状态
if (http.readyState == 4) {
返回的数据都是string
console.log(typeof http.responseText);
console.log(http.response);
字符串类型的json数据转化为对象型json JSON.parse()
var data = JSON.parse(http.response);
console.log(data);
对象json转化为string json JSON.stringify
var strdata=JSON.stringify(data);
console.log(strdata);
}
二、原生Ajax的封装
function method(meth, url, data, async, callback) {
//对象的创建
var http = new XMLHttpRequest();
//判断
if (meth == "get") {
//get 传递的数据在路径的后边 www.baidu.com?name=1&s=2
if (data) {
url += "?";
url += data;
}
http.open(meth, url, async);
http.send();
}
else {
http.open(meth, url, async);
//判断是否有数据
if (data) {
http.send(data);
}
else {
http.send();
}
}
//响应
http.onreadystatechange = function () {
//状态的判断
//状态码 200 success 500 服务器报错 404 服务器端页面丢失
if (http.readyState == 4 && http.status == 200) {
//将请求的数据返回
callback(http.response);
}
}
}
注意:原生js 尽量不要同步,因为原生js是单线程的,会造成线程堵死。
三、跨域问题
在建立好服务器之后,链接服务器会产生跨域的问题。
原因:
1、协议不一致会产生跨域
2、端口不一致也会导致跨域
3、域名不一致也会产生跨域
跨域的解决办法:cross跨域和jsonp跨域
cross跨域
本意是资源共享,在后端进行配置,配置完成之后可以直接访问。
例如php 在后端文件里面写入一句话 header("Access-Control-Allow-Origin: * ");
【 * 代表所有】
jsonp跨域
在原生js里面叫src跨域,即直接通过路径来实现跨域。在前端上使用src进行跨域,在接口上传入要执行的回调函数(后台一定要处理回调函数,这样,前台的函数才有响应)
练习案例:百度搜索跨域
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.block {
width: 600px;
height: 35px;
font-size: 0;
margin: 10px 20px;
position: relative;
}
.ipt {
position: relative;
width: 498px;
height: 35px;
border-style: none;
box-sizing: border-box;
padding-left: 10px;
font-size: 15px;
border: 1px solid #e4e4e4;
box-sizing: content-box;
}
.search {
position: absolute;
right: 0;
display: inline-block;
width: 90px;
height: 36px;
border-style: none;
color: #fff;
font-size: 13px;
text-align: center;
line-height: 36px;
border: 1px solid #43c8ff;
background-color: #43c8ff;
box-sizing: border-box;
cursor: pointer;
}
.menu {
position: absolute;
width: 510px;
height: auto;
border: 1px solid #d6d6d6;
display: none;
font-size: 13px;
}
.menu > li {
list-style: none;
line-height: 23px;
padding-left: 10px;
}
.menu > li > a {
text-decoration: none;
color: #969696;
}
</style>
</head>
<body>
<div class="block">
<input class="ipt" type="text"/>
<a href="" class="search">搜索</a>
<ul class="menu">
</ul>
</div>
<script>
//获取文本框对象
var useript = document.querySelector(".ipt");
var menu = document.querySelector(".menu");
var search = document.querySelector(".search");
var time = null;
useript.onkeyup = function () {
//等一会这里做节流处理
//用户停留20ms 去请求 时间不够不请求
//延迟20ms之后执行的
var that = this;
if (time) {
clearTimeout(time);
}
time = setTimeout(function () {
//该计时器启动意味着 等待时间够了
//按键完成之后获取当前输入的值 this.value
//检测是否开始请求
if (that.value != "") {
//下面百度提供的地址是jsonp跨域的
//直接创建script 添加到网页里面
var infoele = document.getElementsByClassName("getinfo")[0];
if (infoele) {
infoele.remove();
}
var script = document.createElement("script");
script.className = "getinfo";
script.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + that.value + "&cb=getData";
document.body.appendChild(script);
//同时 按键的时候修改 搜索a链接的href 属性
search.href = "https://www.baidu.com/s?wd=" + that.value;
}
else {
menu.style.display = "none";
}
}, 200);
}
//jsonp回调的函数
function getData(result) {
//遍历返回值里面的s数组
var str = "";
for (var i = 0; i < result.s.length; i++) {
str += "<li><a href='https://www.baidu.com/s?wd=" + result.s[i] + "'>" + result.s[i] + "</a></li>";
}
menu.innerHTML = str;
menu.style.display = "block";
}
</script>
</body>
</html>
效果:
通过自己写的搜索框跨域到百度搜索框里,实现跳转。
四、jQuery里的Ajax请求
$.ajax({
method:"get",//请求的方式 type
url:"", //路径
data:{},//传递的参数
dataType:"",//数据类型
jsonpCallback:"",//jsonp 跨域的
success:function (res){
//成功
},
error:function (){
//请求失败
},
async:true//设置同步异步的
});
练习案例:天气预报
五、总结
在Ajax的学习过程中,还是有一些比较绕的东西在里面,需要理解清除它的运行机制,才能更好的掌握Ajax的运用。