5 steps for native ajax requests

What is ajax?


Ajax enables web pages to be updated asynchronously by exchanging a small amount of data with the server in the background. This means that parts of a webpage can be updated without reloading the entire webpage.


Advantages of ajax:


1. Realize partial update (without refresh state)
2. Reduce the pressure on the server side


Disadvantages of ajax:


1. Destroying the browser forward and backward mechanism (because of the ajax automatic update mechanism)
2. If there are too many Ajax requests, the page loading will also be slow.
3. The support of search engines is relatively low.
4. The security problem of ajax is not very good (it can be solved with data encryption).
Note: If you want to use ajax, you must have the support of the back-end environment (server-side).


Five steps for native ajax requests:


1. Instantiate the request object
2. Establish a server link
3. Listen to the server response
4. Send the request
5. The response is successful, and
there are two ways to pass parameters http request:
get: used to get data, get is to pass data on url (URL The things behind), the storage capacity is less, and the safety factor is relatively low.
post: used to upload data, the capacity is almost unlimited (mostly used for forms).

{

    // 1.创建HXMLHttpRequest对象
    var xhr=null;
    //  var xhr = new XMLHttpRequset();
    if(window.XMLHttpRequest){
        xhr=new XMLHttpRequest();// ie7+等现代浏览器
    }else if(window.ActiveXObject){
        // ie6 ,老版本 Opera
        xhr=new ActiveXObject('Microsft.XMLHttp')
    }

    // 2.创建新的http请求,指定请求方法、url及验证信息
    xhr.open("get/post",'https://www.baidu.com/',true) //true表示异步,可以省略

    // 3.设置请求头,get方式不需要
    // post需要设置请求头
    xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    // 若为同步,此代码不用写,直接在send后,用xhr.responseText

    // 5.相应成功,传递参数   并监听
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            // 获取异步返回的json数据
            xhr.responseText
            xhr.responseXML.children[0].children
            JSON.parse(xhr.responseText)//字符串转对象
        }
    }
    
    // 4.发送HTTP请求
    // post 传参数,get 不传参数
    xhr.send('user'+value)

    
}

Guess you like

Origin blog.csdn.net/m0_60237095/article/details/128056188