ajax

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的上的使用

 

              //引入ajax.js
    

 

7.在jquery中发送ajax

 

           //引入jquery.js,里面封装好了ajax
    

 

 

 

 

 

 

你可能感兴趣的:(ajax)