Home Web Front-end JS Tutorial How to use native js to implement Ajax

How to use native js to implement Ajax

Jul 14, 2018 am 09:34 AM
ajax javascript

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()`之后,请求就会被分配到服务器
    Copy after login
  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`状态的说明;
    Copy after login

/**
 * 原生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()之后,请求就会被分配到服务器
}
Copy after login
/**
 * 支持更早期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.")
    }
}
Copy after login
window.onload = function(){
    var btn = document.getElementById("btn1");
    btn.onclick = function(){
        ajax('a.txt', function fnSucc(str){
            alert(str)
        });
    }
}
Copy after login

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 of this Website
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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

How to solve the 403 error encountered by jQuery AJAX request

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

How to solve jQuery AJAX request 403 error

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

How to get variables from PHP method using Ajax?

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQuery AJAX error 403?

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

PHP vs. Ajax: Solutions for creating dynamically loaded content

Understanding Ajax Frameworks: Explore Five Common Frameworks Understanding Ajax Frameworks: Explore Five Common Frameworks Jan 26, 2024 am 09:28 AM

Understanding Ajax Frameworks: Explore Five Common Frameworks

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

Asynchronous data exchange using Ajax functions

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

PHP and Ajax: Ways to Improve Ajax Security

See all articles