


A brief introduction to writing ajax by yourself without using a library (framework)
This article introduces to you how to write ajax without a library (framework). Friends who are interested can learn together.
Usually, ajax is used to request data and load a library (framework). Maybe just maybe. Used the ajax part of it.
Write ajax. Firstly, you can experience the process of solving problems and improve your technical skills. Secondly, sometimes you really don’t need such a large library (framework) at work. Why not write it yourself? Why.
Let’s first take a look at how the popular jQuery calls ajax
$.ajax({ url: 'test.php', //发送请求的URL字符串 type: 'GET', //发送方式 dataType: 'json', //预期服务器返回的数据类型 xml, html, text, json, jsonp, script data: 'k=v&k=v', //发送的数据 async: true, //异步请求 cache: false, //缓存 timeout: 5000, //超时时间 毫秒 beforeSend: function(){}, //请求之前 error: function(){}, //请求出错时 success: function(){}, //请求成功时 complete: function(){} //请求完成之后(不论成功或失败) });
Is such a call very comfortable and convenient? If you feel comfortable Then you can also refer to this design method when writing it yourself. It doesn't need to be too complicated, just meet your needs.
First understand the basic knowledge of ajax
XMLHttpRequest object
The XMLHttpRequest object is the core of ajax. It sends asynchronous requests to the server through the XMLHttpRequest object. The server gets the data and all modern browsers (IE7, Firefox, Chrome, Safari, Opera) support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject).
Create a compatible XMLHttpRequest object
var xhr = window.XMLHttpRequest? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
Send a request to the server
xhr.open(method,url,async);
//method: type of request; GET or POST
//url: Requested URL
//async: true (asynchronous) or false (synchronous)
xhr.send(string);
//Send the request to the server
//string: only for POST Request
//GET is simpler and faster than POST request, and can be used in most cases
//In the following situations, please use POST request:
//Cache files cannot be used (Update files or databases on the server)
//Send a large amount of data to the server (POST has no data limit)
//POST is more stable and reliable than GET when sending user input containing unknown characters
Server response
Use the responseText or responseXML attribute of the XMLHttpRequest object to obtain the response from the server.
If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute.
If the response from the server is not XML, use the responseText property, which returns the response as a string.
onreadystatechange event
When a request is sent to the server, we need to perform some response-based tasks. Whenever readyState changes, the onreadystatechange event is triggered. The readyState attribute stores the status information of XMLHttpRequest.
Three important attributes of the XMLHttpRequest object:
onreadystatechange //Storage function (or function name), Whenever the readyState attribute changes, this function will be called
readyState //The state of the XMLHttpRequest is stored, changing from 0 to 4
0: The request is not initialized
1: The server connection has been established
2: The request has been received
3: The request is being processed
4: The request has been completed and the response is ready
status //200: "OK", 404: Page not found
In the onreadystatechange event, we stipulate that when the server response is ready, it will be processed Tasks performed during preparation. When readyState is equal to 4 and status is 200, it means that the response is ready.
xhr.onreadystatechange = function(){ if( xhr.readyState == 4 && xhr.status == 200 ){ //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML } };
A simple ajax request is as follows:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.onreadystatechange = function(){ if( xhr.readyState == 4 && xhr.status == 200 ){ //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML } }; xhr.open(method,url,async); xhr.send(string);
Supplement: 1. When sending a GET request, you may get cached results. To avoid this, you can add a unique ID and timestamp to the URL. 2. If you need to POST data like an HTML form, use setRequestHeader() to add HTTP headers. Then send the data in the send() method.
url += (url.indexOf('?') < 0 ? '?' : '&') + '_='+ (+new Date()); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Start writing your own ajax
Write a basic one first , define various parameter options, for reference
var $ = (function(){ //辅助函数 序列化参数 function param(data){ //.. } function ajax(opts){ var _opts = { url : '/', //发送请求URL地址 type : 'GET', //发送请求的方式 GET(默认), POST dataType : '', //预期服务器返回的数据类型 xml, html, text, json, jsonp, script data : null, //发送的数据 'key=value&key=value', {key:value,key:value} async : true, //异步请求 ture(默认异步), false cache : true, //缓存 ture(默认缓存), false timeout : 5, //超时时间 默认5秒 load : function(){}, //请求加载中 error : function(){}, //请求出错时 success : function(){}, //请求成功时 complete : function(){} //请求完成之后(不论成功或失败) }, aborted = false, key, xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); for(key in opts) _opts[key] = opts[key]; /* if(_opts.dataType.toLowerCase() === 'script'){ //.. } if(_opts.dataType.toLowerCase() === 'jsonp'){ //.. } */ if(_opts.type.toUpperCase() === 'GET'){ if(param(_opts.data) !== ''){ _opts.url += (_opts.url.indexOf('?') < 0 ? '?' : '&') + param(_opts.data); } !_opts.cache && ( _opts.url += (_opts.url.indexOf('?') < 0 ? '?' : '&') + '_='+(+new Date()) ); } function checkTimeout(){ if(xhr.readyState !== 4){ aborted = true; xhr.abort(); } } setTimeout(checkTimeout, _opts.timeout*1000); xhr.onreadystatechange = function(){ if( xhr.readyState !== 4 ) _opts.load && _opts.load(xhr); if( xhr.readyState === 4 ){ var s = xhr.status, xhrdata; if( !aborted && ((s >= 200 && s < 300) || s === 304) ){ switch(_opts.dataType.toLowerCase()){ case 'xml': xhrdata = xhr.responseXML; break; case 'json': xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')'); break; default: xhrdata = xhr.responseText; } _opts.success && _opts.success(xhrdata,xhr); }else{ _opts.error && _opts.error(xhr); } _opts.complete && _opts.complete(xhr); } }; xhr.open(_opts.type,_opts.url,_opts.async); if(_opts.type.toUpperCase() === 'POST'){ xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } xhr.send(_opts.type.toUpperCase() === 'GET' ? null : param(_opts.data)); } return { ajax: ajax } })();
After defining the parameter options, let’s analyze it. Among them, dataType is the focus of the entire ajax, and it determines whether the code is simple or complex.
Here dataType is the data type expected to be returned by the server: xml, html, text, json, jsonp, script
1. When it is xml, the response from the server is XML, use the responseXML attribute Get the returned data
2. When it is html, text, or json, use the responseText attribute to get the returned data
a. 为html时,返回纯文本HTML信息,其中包含的script标签是否要在插入dom时执行 ( 代码复杂度+3 )
b. 为json时, 返回JSON数据,要安全、要便捷、要兼容 ( 代码复杂度+2 )
3. 为jsonp时,一般跨域才用它,不用原来的ajax请求了,用创建script法( 代码复杂度+2 )
4. 为script时: 要跨域时,不用原来的ajax请求了,用创建script法( 代码复杂度+1 ); 不跨域,返回纯文本JavaScript代码, 使用 responseText 属性获取返回的数据 ( 代码复杂度+1 )
其中,在html片段中的script标签、jsonp、script,都要用到创建script标签的方式。
处理dataType为json
xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')');
这是最简单的处理方式了,要JSON兼容,可以用json2.js。
处理dataType为jsonp
jsonp是要通过script标签来请求跨域的,先了解下流程:
这上图中 a.html中请求了 http://www.b.com/b.php?callback=add (在ajax程序中请求url就是这个链接),在b.php中读取了传过来的参数 callback=add 根据获取到的参数值(值为add),以JS语法生成了函数名,并把json数据作为参数传入了这个函数,返回以JS语法生成的文档给a.html,a.html解析并执行返回的JS文档,调用了定义好的add函数。
在程序中一般采用更通用的方式去调用,比如下面这个广泛使用的loadJS函数:
function loadJS(url, callback) { var doc = document, script = doc.createElement('script'), body = doc.getElementsByTagName('body')[0]; script.type = 'text/javascript'; if (script.readyState) { script.onreadystatechange = function() { if (script.readyState == 'loaded' || script.readyState == 'complete') { script.onreadystatechange = null; callback && callback(); } }; } else { script.onload = function() { callback && callback(); }; } script.src = url; body.appendChild(script); }
这样把请求的url,传入loadJS函数,得到一样的结果。
loadJS('http://www.b.com/b.php?callback=add');
因为是动态创建script,请求成功返回,JS代码就立即执行,如果请求失败是没有任何提示的。因此自定义的参数选项: _opts.success 能调用,_opts.error不能调用。
ajax处理jsonp也有两种情况:
1. 设置了请求URL后的参数 callback=add 特别是定义了函数名add,请求成功返回,JS代码就立即执行(这里就是调用 add({"a":8,"b":2}) )
2. 在_opts.success中处理JSON数据,就是请求成功返回,JS代码不执行,并把函数中的参数挪出来,作为_opts.success的参数返回( 这里相当于处理字符串 'add({"a":8,"b":2})' ,去掉 'add(' 和 ‘)',得到 {"a":8,"b":2} )
处理dataType为html
如果不处理HTML片段中script标签,直接把responseText返回值插入DOM树就可以了。如果要处理script,就要把HTML片段中的script标签找出来,对买个script单独处理,并注意是script标签中包含的JS代码还是通过src请求的。
处理dataType为script
如果要跨域时,用创建script的方式,和处理jsonp类似; 不跨域,使用 responseText 属性获取返回的数据,可以用 eval 来让代码执行,也可以创建script来执行。
function addJS(text) { var doc = document, script = doc.createElement('script'), head = doc.getElementsByTagName('body')[0]; script.type = 'text/javascript'; script.text = text; body.appendChild(script); }
到此ajax差不多分析完了,根据实际需要,添加各种功能,去思考每种功能是怎样实现的,并能找到解决方法。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
初步了解JavaScript,Ajax,jQuery,并比较三者关系
The above is the detailed content of A brief introduction to writing ajax by yourself without using a library (framework). For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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.

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download
The most popular open source editor

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