Home  >  Article  >  Web Front-end  >  How to use native js to implement Ajax

How to use native js to implement Ajax

不言
不言Original
2018-07-14 09:34:431338browse

This article mainly introduces how to use native js to implement Ajax. It has certain reference value. Now I share it with you. Friends in need can refer to it

  1. Create Ajax Object

  2. Connect to server

  3. Send request

       - `send()`接受一个参数(作为请求主体发送的数据),如果没有数据则必须传入`null`,因为这个参数对有些浏览器来说是必须的。调用`send()`之后,请求就会被分配到服务器
  4. Receive return

      - 客户端和服务器端有交互的时候会调用`onreadystatechange`
      - oAjax.`readyState`  **表示请求/响应过程的当前活动阶段**。
           - 0->(未初始化):还没有调用 `open()` 方法。
           - 1->(载入):已调用 `send()` 方法,正在发送请求。
           - 2->载入完成):`send()` 方法完成,已收到全部响应内容。
           - 3->(解析):正在解析响应内容。
           - 4->(完成):响应内容解析完成,可以在客户端调用。
    
      - `responseText`:作为响应主体被返回的文本;
      - `responseXML`:若响应的内容类型是`"text/xml"`或`"application/xml"`,该属性中将保存着包含着响应数据的`XML DOM`文档
      - `status`:响应的`HTTP`状态;
      - `statusText`:`HTTP`状态的说明;

/**
 * 原生js实现Ajax
 * @param url
 * @param fnSucc
 */
function ajax(url, fnSucc){
    if(window.XMLHttpRequest){
        var XHR = new XMLHTTPRequest();
    }else{
        var XHR = new ActiveXObject("Microsoft.XMLHTTP");//IE6浏览器创建ajax对象
    }
    // readystate值每次改变,都会触发readystatechange事件
    // 通常我们只对readstate值为4的阶段感兴趣
    // 不过,必须在调用open()之前指定onreadystatechange事件处理程序,才能确保跨浏览器兼容性。
    XHR.onreadystatechange = function(){
        if(XHR.readyState == 4){
            if(XHR.status >= 200 && XHR.status <= 300 || XHR.status == 304){
                fnSucc(XHR.responseText);//成功的时候调用这个方法
            }else{
                if(fnFiled){
                    fnFiled(XHR.status);
                }
            }
        }
    }
    XHR.open("GET", url, true);//把要读取的参数的传过来, true:异步,false:同步
    XHR.send(null);// send接受一个参数(作为请求主体发送的数据),如果没有数据则必须传入null,因为这个参数对有些浏览器来说是必须的。调用send()之后,请求就会被分配到服务器
}
/**
 * 支持更早期IE版本 IE5+
 * @returns {XMLHttpRequest}
 */
function createXHR(){
    if(typeof XMLHttpRequest != "undefined"){
        return new XMLHttpRequest();
    } else if(typeof ActiveXObject != "undefined"){
        if(typeof arguments.callee.activeXString != "string"){
            var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"],
                i, len = versions.length;
            for(i = 0; i < len; i++){
                new ActiveXObject(versions[i]);
                arguments.callee.activeXString = versions[i];
                berak;
            }
        }
    } else {
        throw new Error("No XHR object available.")
    }
}
window.onload = function(){
    var btn = document.getElementById("btn1");
    btn.onclick = function(){
        ajax('a.txt', function fnSucc(str){
            alert(str)
        });
    }
}

The above is the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Analysis of angular component communication

The above is the detailed content of How to use native js to implement Ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn