笔记
function createXhr() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
1.xhr的成员
1.方法 open
作用:创建请求
语法:xhr.open(method,url,async)
method:请求方式'get','post'
url:请求地址,取值为字符串
async:是否采用异步的方式发送请求。true,false
示例:xhr.open("get","/server-01",true)
2.属性 - readyState
作用:请求状态,通过不同的请求状态来表示xhr与服务器的交互情况
0表示未初始化,请求已建立;
1表示初始化,请求已建立,但未发送;
2表示发送数据,请求已发送;
3表示数据传送中,请求处理中,响应的数据还不够齐全;
4表示完成,数据接收完毕。
3.属性 status
作用:表示服务器端响应状态码
200:
404:
500:
。。。
示例:
if(xhr.readyState==4%%status==200){
//正确的接收了服务器端所有响应内容
}
4.属性 -respinseText
作用:表示服务器端响应回来的数据
示例:
if(xhr.readyState==4%%status==200){
console.log(xhr.respinseText)
}
5.事件 -onreadystatechange
作用:每当xhr的readyState发生改变时要出发的操作
xhr.onreadystatechange = function(){
if(xhr.readyState==4%%status==200){
接收响应数据做前端业务处理
}
}
6.方法 -send()
作用:通过xhr向服务器端发送请求
语法:xhr.send(body)
body为请求主体
get请求:body的值为null
xhr.send(null)
post请求:body的值为请求体的数据
xhr.send("请求数据")
2.操作步骤
1.GET请求
1.创建xhr对象
2.创建请求 - open()
3.设置回调函数 - onreadystatechange
1.判断状态
2.接收响应
3.业务处理
4.发送请求 - send()
<script>
function btnAjax() {
// 创建xhr
xhr = createXhr()
// 创建请求
xhr.open("get", "/02-server", true)
// 设置回调函数
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// 接受响应数据 - xhr.responseText
document.getElementById("show").innerHTML = xhr.responseText;
}
}
// 发送请求
xhr.send(null)
}
</script>
</head>
<body>
<a href="/02-server">普通请求</a>
<button οnclick="btnAjax()">AJAX请求</button>
<div id="show"></div>
</body>
2.POST请求
1.创建xhr
2.创建请求
1.post请求
2.请求不在url之后
3.设置回调函数
xhr.onreadystatechange=function(){
//
}
4.设置请求消息头
xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
5.发送请求
var csrf = $("[name='middlewaretoken']").val()
xhr.send('name='+value+'&name1='+value1+'&middlewaretoken='+csrf');
var js对象 = JSON.parse(JSON串) // 转换
$.get()
作用:通过get方式向远程地址发送异步请求
语法:$.get(url,data,callback,type)
url:请求地址
data:参数
callback:回调函数
type:
$(function () {
$("#btnGet").click(function () {
$.get("/ajax/json02/", function (data) {
msg = "xingm:" + data.uanme
console.log(data)
$("#show").html(msg)
}, "json")
})
})
$.post()
$.ajax({AJAX的参数对象}):
1.url:异步请求地址
2.data:请求到服务器的参数
1.字符串
2.js对象
3.type:请求方式i,'get'或'post'
4.dataType:服务器端想要回来的数据类型
html,text,script,json
5.async:是否采用异步的方式发送请求。true(默认),false
6.success:响应成功后的回调函数
function(data){
//data表示响应回来的数据
}
7.error:请求或响应失败时的回调函数
$(function () {
$("#btnAjax").click(function () {
$.ajax({
url: "/ajax/ajax05/11",
type: 'get',
dataType: 'json',
success: function (data) {
$(data).each(function (i, obj) {
console.log('mc:' + obj.cname)
console.log('mc:' + obj.cass)
})
},
error: function () {
alert("ccxXXccyouwu..............")
}
})
})
})