1.同步和异步
(1)同步:事情一件一件的做
(2)异步:事情可以同时做,前一件事情的执行,不会影响后一件事情的执行
2.XMLHttpRequest对象
var xhr =new XMLHttpRequest()
3.发送get请求
(1)创建XMLHttpRequest对象(2)发送请求
请求行:xhr.open(“get”,url,true)
请求头:get请求不需要设置请求头,按浏览器默认的就可以
请求体:get请求没有请求体 xhr.send()
var bt = document.getElementById('bt') bt.onclick = function () { var xhr =new XMLHttpRequest() xhr.open("get", "02-get.php?username=pp&password=123456") xhr.send() }
4.发送post请求
(1)创建XMLHttpRequest对象
(2)发送请求
请求行:xhr.open("post",url,true)
请求头:post请求有请求体,需要在请求行中设置请求体的编码方式
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
请求体: xhr.send(请求体)
bt.onclick = function () { var xhr =new XMLHttpRequest() xhr.open("post", "02-post.php") xhr.setRequestHeader("content-type","application/x-www-form-urlencoded") xhr.send("username=pp&password=123456") }
5.ajax请求的xhr.readyStat
(1)xhr.readyState = 4时,响应完成
(2)xhr.onreadystatechange 监听readystate值的变化
(3)xhr.status 响应状态码 200代表响应成功
var bt = document.getElementById('bt') bt.onclick = function () { var xhr =new XMLHttpRequest() xhr.open("post", "02-post.php") xhr.setRequestHeader("content-type","application/x-www-form-urlencoded") xhr.send("username=pp&password=123456") xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status===200){ console.log(xhr.responseText) } } } }
6.ajax.js的上的使用
<script src="./ajax.js"></script> //引入ajax.js <script> var bt = document.getElementById('bt') bt.onclick = function () { $.ajax({ //调用 $.ajax()方法 type: "get", url: "./aa.php", dataType: "json", data: { username: "pp", password: 123456 }, success: function (info) { console.log(info) } }) } </script>
7.在jquery中发送ajax
<script src="./jquery.js"></script> //引入jquery.js,里面封装好了ajax <script> var bt = document.getElementById('bt') bt.onclick = function () { $.ajax({ type: "get", url: "./aa.php", dataType: "json", data: { username: "pp", password: 123456 }, success: function (info) { console.log(info) } }) } </script>
浙公网安备 33010602011771号