XmlHttpResquest Object Description

The main object method 1. XmlHttpRequest

void open(String method,String url,Boolen async)  // 用于创建请求
     // method:请求方式(字符串类型),如:GET、POST、DELETE、PUT、DELETE...
     // url:要请求的地址(字符串类型)
    // async:是否同步(布尔类型)

void send(String body)  // 用于发送请求
    // body:要发送的数据(字符串类型)

void setRequestHeader(String header,String value)  // 用于设置请求头
    // header:请求头的key(字符串类型)
    // value:请求头的value(字符串类型)

String getAllResponseHeaders()  // 获取所有响应头,返回响应头数据(字符串类型)

String getAllResponseHeader(String header)  // 获取响应头中指定header的值
    // header:响应头的key(字符串类型)
    // 返回值:响应头中指定的header对应的值

void abort()  // 终止请求

The main attribute of the object 2. XmlHttpResquest

Number readyState  // 状态值(整数)
  • 0: not initialized, open () method has not been called;
  • 1: Start calling the open () method, send () method is not called;
  • 2: send the call has been send () method, no response is received;
  • 3: receiving portion has received the response data
  • 4: complete, all of the response data has been received
Function onreadystatechange  // 当readyState的值改变时自动触发执行其对应的函数(回调函数)

String responseText  // 服务器返回的数据(字符串类型)

XmlDocument responseXML  // 服务器返回的数据(Xml对象)

Number states  // 状态码(整数),如:200、404

String statesText  // 状态文本(字符串),如:OK、NotFound...

3. Send a GET request

<script>
    function Ajax1(){
    var xhr = new XMLHttpRequest();  // 创建对象
    // 设置回调函数,一定要在send上面配置
    xhr.onreadystatechange = function(){
        // 当某个状态(0-4)更改时函数自动执行
        if(xhr.readyState == 4){
            // 接收完毕,服务器返回的数据
            xhr.responseText  // 返回的文本信息
        }
    }
    xhr.open('GET','/test/');  // 请求方式,创建连接,
    xhr.send(null)  // 发送,null表示什么都不发
}
</script>

4. POST request sent

<script>
    function Ajax2(){
    var xhr = new XMLHttpRequest();  
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            console.log(xhr.responseText)
        }
    };
    xhr.open('POST','/test/');  // 请求方式,创建连接,
    xhr.setRequestHeader('Content_type','application/x-www-form-urlencoded; charset-UTF-8')  // 设置请求头
    xhr.send('n1=123;n2=456;')  // 发送数据
}
</script>

Guess you like

Origin www.cnblogs.com/863652104kai/p/11489178.html