Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write ajax without framework

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

How to achieve without the framework to write their own ajax, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Ajax is usually used to request data, load a library (framework), or just maybe uses its ajax part.

Write an ajax, on the one hand, you can go through the process of dealing with problems and improve your technical skills, and on the other hand, sometimes you don't need such a large library (framework) at work. Why not write it yourself?

Let's first take a look at how the popular jQuery calls ajax.

$.ajax ({url: 'test.php', / / the URL string for sending the request type:' GET', / / sending method dataType: 'json', / / the data type returned by the expected server: xml, html, text, json, jsonp, script data:' karma, async: true, / / data sent: true, / / Asynchronous request cache: false / / cache timeout: 5000, / / timeout millisecond beforeSend: function () {}, / / error: function () {} before request, / / success: function () {} when request goes wrong, / / complete: function () {} / / after request completion (regardless of success or failure))

Such a call is not very comfortable, convenient, if you feel comfortable, then do-it-yourself writing also refer to this kind of design, not too complicated, just meet the needs.

First understand the basics of ajax

XMLHttpRequest object

XMLHttpRequest object is the core of ajax, which sends asynchronous requests to the server and obtains data from the server through XMLHttpRequest objects. All modern browsers (IE7+, Firefox, Chrome, Safari, Opera) support XMLHttpRequest objects (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: the requested URL

/ / async:true (asynchronous) or false (synchronous)

Xhr.send (string)

/ / send the request to the server

/ / string: for POST requests only

/ / GET is simpler and faster than POST request, and can be used in most cases

/ / use the POST request in the following situations:

/ / cannot use cache files (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 property of the XMLHttpRequest object to get a response from the server.

If the response from the server is XML and needs to be resolved as a XML object, use the responseXML property.

If the response from the server is not XML, use the responseText property, which returns a response as a string.

Onreadystatechange event

When the request is sent to the server, we need to perform some response-based tasks. Whenever the readyState changes, the onreadystatechange event is triggered. The readyState property stores the status information of the XMLHttpRequest.

Three important properties of the XMLHttpRequest object:

Onreadystatechange / / stores the function (or function name), which is called whenever the readyState property changes

ReadyState / / has the status of XMLHttpRequest, changing from 0 to 4

0: request is not initialized

1: the server connection has been established

2: the request has been received

3: request processing

4: the request has been completed and the response is ready

Status / / 200: "OK", 404: page not found

In the onreadystatechange event, we specify the task to be performed when the server responds when it is ready to be processed, and when readyState equals 4 and status equals 200, the response is ready.

Xhr.onreadystatechange = function () {if (xhr.readyState = = 4 & & xhr.status = = 200) {/ / ready to process the returned xhr.responseText or 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) {/ / ready to process the returned xhr.responseText or xhr.responseXML}; xhr.open (method,url,async); xhr.send (string)

Supplement: 1. You may get cached results when you send a GET request, and to avoid this, add a unique ID, timestamp, to the URL. two。 If you need POST data like the HTML form, use setRequestHeader () to add the HTTP header. The data is then sent in the send () method.

Url + (url.indexOf ('?')

< 0 ? '?' : '&') + '_='+ (+new Date());xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');   开始写自己的ajax   先写一个基本的,定义好各种参数选项,供参考 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 }})();   定义好了参数选项,来分析一下。其中 dataType 是整个ajax的重点,代码的简单或者复杂都在它了。   在这里dataType为预期服务器返回的数据类型:xml, html, text, json, jsonp, script   1. 为xml时,来自服务器的响应是XML,使用 responseXML 属性获取返回的数据   2. 为html、text、json时,使用 responseText 属性获取返回的数据       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标签来请求跨域的,先了解下流程:

In the figure above, http://www.b.com/b.php?callback=add is requested in a.html (url is the link requested in the ajax program), and the passed parameter callback=add is read in b.php. According to the obtained parameter value (the value is add), the function name is generated in JS syntax, and the json data is passed into the function as an argument to return the document generated in JS syntax to a.html. A.html parses and executes the returned JS document, calling the defined add function.

It is generally called in a more general way in programs, such as the following widely used loadJS function:

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);}

So pass the requested url into the loadJS function and get the same result.

The copy code is as follows:

LoadJS ('http://www.b.com/b.php?callback=add');

Because the script is created dynamically, if the request returns successfully, the JS code executes immediately, without any hint if the request fails. Therefore, the custom parameter option: _ opts.success can be called, and _ opts.error cannot be called.

There are also two situations in which ajax handles jsonp:

1. The parameter callback=add after the request URL is set, especially the function name add is defined. If the request returns successfully, the JS code will be executed immediately (in this case, the call add ({"a": 8, "b": 2}))

two。 When the JSON data is processed in _ opts.success, the request is returned successfully, and the JS code is not executed, and the parameters in the function are removed and returned as parameters of _ opts.success (here equivalent to processing the string 'add ({"a": 8, "b": 2})', removing the 'add (' and') 'and getting {"a": 8, "b": 2})

Processing dataType to html

If you don't deal with the script tag in the HTML fragment, just insert the responseText return value into the DOM tree. If you want to deal with script, you need to find the script tag in the HTML fragment, deal with buying a script separately, and note that the JS code contained in the script tag is requested through src.

Processing dataType to script

If you want to cross-domain, create a script in the same way as dealing with jsonp; without cross-domain, use the responseText attribute to get the returned data, you can use eval to make the code execute, or you can create a script to execute.

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);} is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report