一、什么是Ajax
AJAX即“Asynchronous Javascript And XML”( 异步 JavaScript和XML),
AJAX不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的 Web 应用程序的技术。
它是一套综合了多项技术的浏览器端网页开发技术。
这些技术包括Javascript、XHTML和CSS、DOM、XML和XMLHttpRequest.
简述就是,只需与服务器进行少量的数据交互,不用刷新整个页面,就可实现页面的更新。
二、Ajax原理
运用HTML和css来实现页面,表达信息
通过浏览器的XmlHttpRequest(Ajax引擎)对象

三、原生ajax
<script type="text/javascript">
// 1:创建XMLHttpRequest对象
var xhr = null;
// if (window.XMLHttpRequest) {
// //兼容主流浏览器
// xhr = new XMLHttpRequest();
// } else{
// //兼容ie6 ie5
// xhr = new ActiveXObject("Microsoft.XMLHTTP")
// }
try{
xhr = new XMLHttpRequest();
}catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP")
}
// es3异常处理 解决错误 异常 try catch finally || throw 异常
// try{
// a+1;
// }catch(e){
// console.log(e.toString())
// }finally{
// console.log("一定会执行的部分")//释放资源
// }
console.log(xhr)
console.log(xhr.readyState+"0")
// 2:建立连接
xhr.open("get","http://localhost:3333/",true)
console.log(xhr.readyState+"1")
// 3:发送请求
xhr.send(null)
console.log(xhr.readyState+"2")
// 4:获取响应的数据
xhr.onreadystatechange=function () {
console.log(xhr.readyState+"3")
if (xhr.readyState==4) {
console.log(xhr.readyState+"4")
if (xhr.status==200) {
console.log(xhr.readyState+"5")
var data =JSON.parse(xhr.responseText) ;
console.log(xhr.readyState+"6")
console.log(data)
show(data);
} else{
console.log("网络请求失败")
}
}
}
function show (data) {
console.log(data)
document.getElementById("div1").innerHTML=data;
}
</script>
三、封装的ajax
<script src="js/jquery-3.1.1.js" ></script>
<script type="text/javascript">
$.ajax({
type:"get",
url:"http://localhost:3333/",
async:true,
dataType:"json",
timeout:3000,
beforeSend:function(){
console.log("最先加载")
},
success:function (data) {
console.log(data)
},
error:function () {
console.log("网络错误")
},
complete:function () {
console.log("最后一定要执行的地方")
}
});
/*$.getJSON("http://localhost:3333/",{
name:"aaa",
age:18
},function (data) {
console.log(data)
})*/
/*$.get("http://localhost:3333/",{
name:"aaa",
age:18
},function (data) {
var data=JSON.parse(data)
console.log(data)
})*/
$.post("http://localhost:3333/",{
name:"aaa",
age:18
},function (data) {
var data=JSON.parse(data)
console.log(data)
})
</script>
四、ajax 和json的区别

本文介绍了Ajax技术的概念及其工作原理,展示了如何使用原生JavaScript和jQuery库实现Ajax请求,并探讨了Ajax与JSON之间的区别。
428

被折叠的 条评论
为什么被折叠?



