In data-based applications, the data required by users, such as contact lists, can be obtained from a server independent of the actual web page and can be dynamically written into the web page, coloring the slow web application experience and making it look like a desktop Same application. Since js has various frameworks, such as jquery, using ajax has become quite simple. But sometimes in order to pursue simplicity, there may be no need to load a huge js plug-in like jquery in the project. But what should I do if I want to use ajax function? Let me share with you several ways to use javascript to implement native ajax.
First, you must create an XMLHttpRequest object before implementing ajax. If the browser that creates the object is not supported, you need to create an ActiveXObject. The specific method is as follows:
var xmlHttp; function createxmlHttpRequest(){ if(window.ActiveXObject){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest) xmlHttp=new XMLHttpRequest(); }
The following uses the xmlHttp created above to implement the simplest ajax get request:
function doGet(url){//注意在传参数值的时候最好使用encodeURI处理一下,防止乱码 createxmlHttpRequest(); xmlHttp.open("GET",url); xmlHttp.send(null); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ alert('success'); }else{ alert('fail'); } } }
Uses the xmlHttp created above xmlHttp implements the simplest ajax post request:
function doPost(url,data){//注意在传参数值的时候最好使用encodeURI处理一下,防止乱码 createxmlHttpRequest(); xmlHttp.open("POST",url); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(data); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ alert('success'); }else{ alert('fail'); } } }
Let’s share an encapsulation of the $.ajax method that simulates jquery seen on the Internet:
var createAjax=function(){ var xhr=null; try{//IE系列浏览器 xhr=new ActiveXObject("microsoft.xmlhttp"); }catch(e1){ try{//非IE浏览器 xhr=new XMLHttpRequest(); }catch(e2){ window.alert("您的浏览器不支持ajax,请更换!"); } } return xhr; }; var ajax=function(conf){ var type=conf.type;//type参数,可选 var url=conf.url;//url参数,必填 var data=conf.data;//data参数可选,只有在post请求时需要 var dataType=conf.dataType;//datatype参数可选 var success=conf.success;//回调函数可选 if(type==null){//type参数可选,默认为get type="get"; } if(dataType==null){//dataType参数可选,默认为text dataType="text"; } var xhr=createAjax(); xhr.open(type,url,true); if(type=="GET"||type=="get"){ xhr.send(null); }else if(type=="POST"||type=="post"){ xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.send(data); } xhr.onreadystatechange=function(){ if(xhr.readyState==4&&xhr.status==200){ if(dataType=="text"||dataType=="TEXT"){ if(success!=null){//普通文本 success(xhr.responseText); } }else if(dataType=="xml"||dataType=="XML"){ if(success!=null){//接收xml文档 success(xhr.responseXML); } }else if(dataType=="json"||dataType=="JSON"){ if(success!=null){//将json字符串转换为js对象 success(eval("("+xhr.responseText+")")); } } } }; }; 该
This method is also very simple to use. It’s the same as jquery’s $.ajax method, but it doesn’t have as many parameters. It just simply implements some basic ajax functions. The usage method is as follows:
ajax({ type:"post",//post或者get,非必须 url:"test.jsp",//必须的 data:"name=dipoo&info=good",//非必须 dataType:"json",//text/xml/json,非必须 success:function(data){//回调函数,非必须 alert(data.name); } });
Have you learned the above methods of javascript to implement native ajax? I hope everyone has to help.
Related recommendations:
How to implement ajax to jump to a new jsp page
jQuery uses ajax to read local json files Case
How to solve the problem of multiple ajax page requests and page loading blocking
The above is the detailed content of Several JavaScript methods to implement native ajax. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

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.

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.

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

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 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 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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool