js native Ajax (xiv)

A, [the XMLHttpRequest use the XMLHttpRequest, must be deployed to a web server html ]
1) assignment request
1, instantiation
eg:

    var http = new XMLHttpRequest();

http XMLHttpRequest object is instantiated, the object can be reused, but this will terminate before any request by the object suspended.

2, designation request
open (method, url, async)
parameters:    
Method: Type of request; like the GET or POST
url: path to the file on the server
the async: true (asynchronous) or false (synchronous) [ defaults to true ]
eg :

    http.open("GET","data.xml");

3, the first setting request [ request body whether the transmitted data to invoke ]
setRequestHeader (key, value);
if there is a request header, the method proceeds to call setting.
Parameters:
    1. Key:   communicating data type attribute
    2 .Value:   corresponding attribute value  
eg:

    // the Content-Type is set to a form format 
    http.setRequestHeader ( "Content-type", "application / x-www-form-urlencoded; charset = UTF-8");

Note:
    the XMLHttpRequest will automatically add the following request header to prevent counterfeiting , we are unable to deliver to setRequestHeader () following request headers.
    The TE-the Content-the Charset the Accept-Encoding Transfer
    the Accept-Encoding a Date Trailer
    Connection the Expect Transfer-Encoding
    the Content-Upgrade the Host the Length
    cookies the Keep-Alive-the User - Agent
    Cookie2 Via the Referer
    
4. specifies an optional request to the main server to send
send (param)
parameters:
    param: request the main content, if not, is null or omitted.
eg:

    / * 
      Sending plain text to the server using the POST method 
    * / 
    function the postMessage (URL, MSG) {
         var Request = new new the XMLHttpRequest (); 
        the request.open ( "POST" , URL); 
        request.setRequestHeader ( "the Content-type", " text / Plain; charset = UTF-. 8 " ); 
        request.send (MSG); 
    }


2) acquisition response
. 1, HTTP status code:
A, [Status returns an HTTP status code in digital form ]    
200 is the OK
404 Not Found
403 Forbidden JSONP [ resolve cross-domain request, the general background processing problem ]
500 background code exception
b, statusText [ returns text HTTP status code ]    
the OK    
Not Found

2, get some information about the response of
the getResponseHeader ()   Gets the response header
the getAllResponseHeaders () Get all response header
responseText                       acquired text form of the response body
responseXML                      acquired Document in the form of the response body
readyState                          returns HTTP [request status whenever readyState changes, it will trigger onreadystatechange event ]

readyState relevant status values:
   open () not called UNSENT
. 1     open () has been called the OPENED
2 receives the header information HEADERS_RECEIVED
. 3    is received in response to the body LOADING
. 4    in response to completion DONE [ in response to completion, can be acquired in response to body ]

3, readystatechange request state change event [ when used in front to be added on eg: onreadystatechnage ]
when changing readyState value of 4 or server response is complete, all browsers triggered the event
eg:

    / * 
      Get the HTTP response 
    * / 
    function getText (URL, the callback) {
         var HTTP = new new the XMLHttpRequest (); 
        http.open ( "the GET" , URL); 
        request.onreadystatechange = function () {
             // If the request is completed, and the request successful 
            IF (http.readyState === === 200 is http.status &&. 4 ) {
                 var type = http.getResponseHeader ( "the Content-type" );
                 IF (type.match (/ ^ text /)) {     // if response text is 
                    the callback (http.responseText); // callback function 
                } 
            }
        };
        http.send(null);
    }

 
3) in response to the decoding
1.MIME type is text / plain, text / html, when text / css text types, may be used responseText attribute resolve
2.MIME type is a type of XML document, using responseXML property parsing
3. If the server object is transmitted, such a configuration data array as a response, he should JSON encoded transmission data string.
By responseText receives it, it can be passed to the JSON.parse () method to resolve the object into js.

Second, the method uses its own primary packaging Ajax
EG:

    function myAjax(method,url,param,success,fail){
        //后台服务器地址及端口号
        var baseUrl =  'http://134.175.154.93:8099';
        //前端传递给后台的参数
        //handle当内部的异步执行成功的回调函数,需要将后台返回的数据交给handle
        //1、创建XMLHttpRequest 对象
        var http = new XMLHttpRequest();
        //处理GET方式携带参数
        if(method === 'GET' && param){
            url += '?'+encodeFormData(param);
        }else{
        
        }
        //2、向服务器发送请求
        http.open(method,baseUrl+url);
        //3、HTTp状态值readystate改变时的响应事件
        http.onreadystatechange = function(){
            //如果HTTP返回状态码为200(请求成功)且返回HTTP状态值为4(响应完成)时执行成功回调函数success()
            if (http.status === 200 && http.readyState === 4) {
                console.log('请求成功!!!');
                success(JSON.parse(http.responseText));    //将返回的JSON字符串解析成js对象并作为回调函数的参数
            }
            //如果返回HTTP状态码不为200(不是请求成功)执行失败回调函数fail()
            if(http.status !== 200){
                fail(http.responseText);
            }
        };
        //处理POST方式携带参数
        if (method === 'POST' && param) {
            //设置请求头其Content-Type类型为表单格式
            http.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');
            //4、将请求发送给服务器并携带数据信息
            http.send(encodeFormData(param));
        }else{
            //4、将请求发送给服务器不携带数据信息
            http.send();
        }
        
    }
    
    //将js的对象转换成表单格式数据
    function encodeFormData(data){
        if(!data){
            return "";
        }
        var pairs = [];
        for(var name in data){
            if(!data.hasOwnProperty(name)){
                continue;
            }
            if(typeof data[name] == "function"){
                continue;
            }
            var value = data[name].toString();
            name = encodeURIComponent(name.replace("%20","+"));//编码名字
            value = encodeURIComponent(value.replace("%20","+"));//编码值
            pairs.push(name+"="+value);
        }
        return pairs.join('&');
    }

 

Guess you like

Origin www.cnblogs.com/nzcblogs/p/11246297.html