AJAX学习(3)---XMLHttpRequest发送请求与取得响应

一、XMLHttpRequest发送请求

XMLHttpRequest发送请求方法

open(method, url, async) send(string) 具体代码举例如下:

// get
request.open(get, 'get.php', true)
request.send()


// post
request.open(post, 'add.php', true);
request.setRequestHeader("Content-Type","application/x-wwwform-urlencoded")
request.send(name=李龙&sex=男)

二、XMLHttpRequest取得响应

以下属性和方法介绍:

reponseText:获得字符串形式的相应数据

reponseXml:获得XML形式的相应数据

status与statusText:以数字与文本形式返回HTTP状态码

getAllResponseHeader():获取所有的响应报头

getResponseHeader():查询响应中某个字段的值

readyState属性值的情况如下:

0:请求初始化,open还未调用

1:服务器连接已建立,open已经调用

2:请求已经收,也就是接收到头信息了

3:请求处理中,也就是接收到响应主体了

4:请求已完成,响应已就绪,也就是响应完成了

代码如下:

var request  = new XMLHttpRequest();
request.open('get', 'add.php', true);
request.send();
request.onreadystatechange = function(){
    if(request.readyState === 4 && request.status === 200){
        // 逻辑梳理 response.responseText
    }
}

备注:在readyState变化的时候,函数会执行。一般是0-4的变化(正常情况)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章