search
HomeWeb Front-endJS TutorialSharing of javascript native ajax writing methods_javascript skills

ajax: a way to request data without refreshing the entire page;
The technical core of ajax is the XMLHttpRequest object;
ajax request process: create XMLHttpRequest object, connect to server, send request, receive response data;

/**
 * 得到ajax对象
 */
function getajaxHttp() {
  var xmlHttp;
  try {
    //chrome, Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
    } catch (e) {
      // Internet Explorer
      try {
        //IE5,6
        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
      try {
        //IE7以上
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("您的浏览器不支持AJAX!");
        return false;
      }
    }
  }
  return xmlHttp;
}
/**
 * 发送ajax请求
 * url--url
 * methodtype(post/get)
 * con (true(异步)|false(同步))
 * parameter(参数)
 * functionName(回调方法名,不需要引号,这里只有成功的时候才调用)
 * (注意:这方法有二个参数,一个就是xmlhttp,一个就是要处理的对象)
 * obj需要到回调方法中处理的对象
 */
function ajaxrequest(url,methodtype,con,parameter,functionName,obj){
  var xmlhttp=getajaxHttp();
  xmlhttp.onreadystatechange=function(){
     
    // readyState值说明 
    // 0,初始化,XHR对象已经创建,还未执行open 
    // 1,载入,已经调用open方法,但是还没发送请求 
    // 2,载入完成,请求已经发送完成 
    // 3,交互,可以接收到部分数据 
  
    // status值说明 
    // 200:成功 
    // 404:没有发现文件、查询或URl 
    // 500:服务器产生内部错误 
 
    if(xmlhttp.readyState==4&& XHR.status == 200){
      //HTTP响应已经完全接收才调用
      functionName(xmlhttp,obj);
    }
  };
  xmlhttp.open(methodtype,url,con);
  xmlhttp.send(parameter);
}
//这就是参数
function createxml(){
  var xml="<user><userid>asdfasdfasdf<\/userid><\/user>";//"\/"这不是大写V而是转义是左斜杠和右斜杠
  return xml;
}
//这就是参数
function createjson(){
  var json={id:0,username:"好人"};
  return json;
}
function c(){
  alert("");
}

//Test

ajaxrequest("http://www.baidu.com","post",true,createxml(),c,document);

Let’s look at another example

ajax({
    url: "./TestXHR.aspx",       //请求地址
    type: "POST",            //请求方式
    data: { name: "super", age: 20 },    //请求参数
    dataType: "json",
    success: function (response, xml) {
      // 此处放成功后执行的代码
    },
    fail: function (status) {
      // 此处放失败后执行的代码
    }
  });

  function ajax(options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || "json";
    var params = formatParams(options.data);

    //创建 - 非IE6 - 第一步
    if (window.XMLHttpRequest) {
      var xhr = new XMLHttpRequest();
    } else { //IE6及其以下版本浏览器
      var xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    //接收 - 第三步
    xhr.onreadystatechange = function () {
      if (xhr.readyState == 4) {
        var status = xhr.status;
        if (status >= 200 && status < 300) {
          options.success && options.success(xhr.responseText, xhr.responseXML);
        } else {
          options.fail && options.fail(status);
        }
      }
    }

    //连接 和 发送 - 第二步
    if (options.type == "GET") {
      xhr.open("GET", options.url + "&#63;" + params, true);
      xhr.send(null);
    } else if (options.type == "POST") {
      xhr.open("POST", options.url, true);
      //设置表单提交时的内容类型
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhr.send(params);
    }
  }
  //格式化参数
  function formatParams(data) {
    var arr = [];
    for (var name in data) {
      arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    }
    arr.push(("v=" + Math.random()).replace(".",""));
    return arr.join("&");
  }

Let’s take a look at the principle

1. Create

1.1, IE7 and above support native XHR objects, so you can use it directly: var oAjax = new XMLHttpRequest();

In 1.2, IE6 and previous versions, the XHR object is implemented through an ActiveX object in the MSXML library. Some books detail three different versions of such objects in IE, namely MSXML2. =new ActiveXObject('Microsoft.XMLHTTP');

2. Connect and send

2.1. Three parameters of the open() function: request method, request address, and whether to request asynchronously (synchronous requests are rare and have not been used so far);

2.2. The GET request method submits data to the server through URL parameters, while POST submits data to the server as send parameters;

2.3. In POST request, before sending data, the content type of form submission must be set;

2.4. Parameters submitted to the server must be encoded through the encodeURIComponent() method. In fact, in the parameter list "key=value", both key and value need to be encoded because they will contain special characters. Each time a request is made, a "v=xx" string will be spelled into the parameter list. This is to refuse caching and request directly to the server every time.

encodeURI(): used for encoding the entire URI. Special characters that are part of the URI will not be encoded, such as colons, forward slashes, question marks, and pound signs; its corresponding decoding function decodeURI();
encodeURIComponent(): used to encode a certain part of the URI, and will encode any non-standard characters it finds; its corresponding decoding function decodeURIComponent();

3. Receive

3.1. After receiving the response, the response data will automatically fill in the XHR object. The relevant attributes are as follows
responseText: the body content returned by the response, which is a string type;
responseXML: If the content type of the response is "text/xml" or "application/xml", this attribute will store the corresponding xml data, which is the document type corresponding to XML;
status: response HTTP status code;
statusText: Description of HTTP status;

3.2. The readyState attribute of the XHR object indicates the current active stage of the request/response process. The value of this attribute is as follows
0 - Not initialized, the open() method has not been called;
1-Start up, the open() method is called, the send() method is not called;
2-Send, the send() method has been called, and no response has been received;
3-Receive, part of the response data has been received;
4-Complete, all response data has been received;

As long as the value of readyState changes, the readystatechange event will be called. (In fact, for logical smoothness, readystatechange can be placed after send, because when sending, requesting the server will cause network communication, which takes time. Specify the readystatechange event after send. Handlers are also possible, I usually use them this way, but for the sake of standardization and cross-browser compatibility, it is better to specify them before opening).

3.3. In the readystatechange event, first determine whether the response is received, and then determine whether the server successfully processed the request. xhr.status is the status code. Status codes starting with 2 are successful. 304 means getting it from the cache. The code adds a random number to each request, so the value will not be retrieved from the cache, so there is no need to judge this status.

4. Ajax requests cannot cross domains!

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)