


Detailed explanation of native JS sending asynchronous data request examples
This article mainly introduces the relevant information of native JS to send asynchronous data requests in detail. It has certain reference value. Interested friends can refer to it
When working on projects, there are Sometimes you need to use asynchronous data requests, but if there is no framework dependency at this time, you need to use native JS for asynchronous data requests. There are only two request methods at this time, one is AJAX and the other is JSONP. Simple encapsulation of asynchronous requests through native JS.
AJAX
AJAX is a data request method that can update the data of a partial page without refreshing the entire page. The technical core of AJAX is the XMLHttpRequest object. The main request process is as follows:
Create XMLHttpRequest object (new)
Connect to the server (open)
Send request(send)
Receive response data(onreadystatechange)
Don’t speak Directly paste the code
/** * 通过JSON的方式请求 * @param {[type]} params [description] * @return {[type]} [description] */ ajaxJSON(params) { params.type = (params.type || 'GET').toUpperCase(); params.data = params.data || {}; var formatedParams = this.formateParams(params.data, params.cache); var xhr; //创建XMLHttpRequest对象 if (window.XMLHttpRequest) { //非IE6 xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步状态发生改变,接收响应数据 xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if (!!params.success) { if (typeof xhr.responseText == 'string') { params.success(JSON.parse(xhr.responseText)); } else { params.success(xhr.responseText); } } } else { params.error && params.error(status); } } if (params.type == 'GET') { //连接服务器 xhr.open('GET', (!!formatedParams ? params.url + '?' + formatedParams : params.url), true); //发送请求 xhr.send(); } else { //连接服务器 xhr.open('POST', params.url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //发送请求 xhr.send(formatedParams); } }, /** * 格式化数据 * @param {Obj} data 需要格式化的数据 * @param {Boolean} isCache 是否加入随机参数 * @return {String} 返回的字符串 */ formateParams: function(data, isCache) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); } if (isCache) { arr.push('v=' + (new Date()).getTime()); } return arr.join('&'); }
IE7 and above support native XHR objects, so you can use it directly: var oAjax = new XMLHttpRequest();. In IE6 and previous versions, the XHR object is implemented through an ActiveXObject object in the MSXML library.
Connect to the server through the open function of xhr, which mainly receives three parameters: request method, request address and whether to request asynchronously (usually asynchronous request). There are two request methods, GET and POST. GET submits data to the server through the URL, and POST sends the data to the server as a parameter of the send method.
Bind the status change function onreadystatechange to xhr, which is mainly used to detect changes in the readyState of xhr. When the asynchronous transmission is successful, the value of readyState will change from 0 to 4, and the onreadystatechange event will be triggered at the same time. The attributes and corresponding states of readyState are as follows:
0 (Uninitialized) The object has been created, but it has not yet been initialized (the open method has not been called)
1 (Initialized) The object has been created, but the send method has not been called yet
2 (Send data) The send method has been called, but the current status and http header are unknown
3 (Data is being transmitted) Part of the data has been received, because the response and http header are incomplete. At this time, obtaining part of the data through responseBody and responseText will appear. Error
4 (Complete) Data reception is completed. At this time, the complete response data can be obtained through responseBody and responseText
In the readystatechange event, first determine whether the response has been received, and then determine whether the server The request is processed successfully, xhr.status is status code, status codes starting with 2 are successful, 304 means obtained from the cache, the above code adds a random number to each request, so The value will not be retrieved from the cache, so this status does not need to be judged.
JSONP
If you still use the above XMLHttpRequest object to send cross-domain requests, although the send function is called, the status of xhr is always 0, and The onreadystatechange event will not be triggered. At this time, the JSONP request method will be used.
JSONP (JSON with Padding) is a cross-domain request method. The main principle is to take advantage of the cross-domain request feature of the script tag, send the request to the server through its src attribute, the server returns the js code, the web page accepts the response, and then executes it directly. This is the same as the principle of referencing external files through the script tag. the same.
JSONP consists of two parts: Callback function and data. The callback function is generally controlled by the web page and sent to the server as a parameter. The server combines the function and data. Return as a string.
For example, the web page creates a script tag and assigns its src value to http://www.test.com/json/?callback=process. At this time, the web page Just make a request. The data to be returned by the server is passed in as the parameter of the function. The data format returned by the server is similar to "process({'name:'xieyufei'})". The web page received the response value because the request The one is script, so it is equivalent to calling the process method directly and passing in a parameter.
Post the code directly without saying anything.
/** * 通过JSONP的方式请求 * @param {[type]} params [description] * @return {[type]} [description] */ ajaxJSONP(params) { params.data = params.data || {}; params.jsonp = params.jsonp || 'callback'; // 设置传递给后台的回调参数名和参数值 var callbackName = 'jsonp_' + (new Date()).getTime(); params.data[params.jsonp] = callbackName; var formatedParams = this.formateParams(params.data, params.cache); //创建script标签并插入到页面中 var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); head.appendChild(script); //创建jsonp回调函数 window[callbackName] = function(json) { head.removeChild(script); clearTimeout(script.timer); window[callbackName] = null; params.success && params.success(json); }; //发送请求 script.src = (!!formatedParams ? params.url + '?' + formatedParams : params.url); //为了得知此次请求是否成功,设置超时处理 if (params.time) { script.timer = setTimeout(function() { window[callbackName] = null; head.removeChild(script); params.error && params.error({ message: '超时' }); }, params.time); } }
When the src attribute is set to the script tag, the browser will send a request, but it can only send the request once, causing the script tag to not be reused, so each operation is completed You need to remove the script tag. Before the browser sends a request, bind a callback function globally. This callback function will be called when the data request is successful.
Summary
Integrate the two methods of sending asynchronous data and determine which method to use based on dataType. Post the complete code
var xyfAjax = { ajax: function(params) { params = params || {}; params.cache = params.cache || false; if (!params.url) { throw new Error('参数不合法'); } params.dataType = (params.dataType || 'json').toLowerCase(); if (params.dataType == 'jsonp') { this.ajaxJSONP(params); } else if (params.dataType == 'json') { this.ajaxJSON(params); } }, /** * 通过JSONP的方式请求 * @param {[type]} params [description] * @return {[type]} [description] */ ajaxJSONP(params) { params.data = params.data || {}; params.jsonp = params.jsonp || 'callback'; // 设置传递给后台的回调参数名和参数值 var callbackName = 'jsonp_' + (new Date()).getTime(); params.data[params.jsonp] = callbackName; var formatedParams = this.formateParams(params.data, params.cache); //创建script标签并插入到页面中 var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); head.appendChild(script); //创建jsonp回调函数 window[callbackName] = function(json) { head.removeChild(script); clearTimeout(script.timer); window[callbackName] = null; params.success && params.success(json); }; //发送请求 script.src = (!!formatedParams ? params.url + '?' + formatedParams : params.url); //为了得知此次请求是否成功,设置超时处理 if (params.time) { script.timer = setTimeout(function() { window[callbackName] = null; head.removeChild(script); params.error && params.error({ message: '超时' }); }, params.time); } }, /** * 通过JSON的方式请求 * @param {[type]} params [description] * @return {[type]} [description] */ ajaxJSON(params) { params.type = (params.type || 'GET').toUpperCase(); params.data = params.data || {}; var formatedParams = this.formateParams(params.data, params.cache); var xhr; //创建XMLHttpRequest对象 if (window.XMLHttpRequest) { //非IE6 xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步状态发生改变,接收响应数据 xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { if (!!params.success) { if (typeof xhr.responseText == 'string') { params.success(JSON.parse(xhr.responseText)); } else { params.success(xhr.responseText); } } } else { params.error && params.error(status); } } if (params.type == 'GET') { //连接服务器 xhr.open('GET', (!!formatedParams ? params.url + '?' + formatedParams : params.url), true); //发送请求 xhr.send(null); } else { //连接服务器 xhr.open('POST', params.url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //发送请求 xhr.send(formatedParams); } }, /** * 格式化数据 * @param {Obj} data 需要格式化的数据 * @param {Boolean} isCache 是否加入随机参数 * @return {String} 返回的字符串 */ formateParams: function(data, isCache) { var arr = []; for (var name in data) { arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name])); } if (isCache) { arr.push('v=' + (new Date()).getTime()); } return arr.join('&'); } } xyfAjax.ajax({ url:'http://www.xieyufei.com', type:'get', //or post dataType:'json', //or jsonp data:{ name:'xyf' }, success: function(data){ console.log(data) } })
The above is the detailed content of Detailed explanation of native JS sending asynchronous data request examples. For more information, please follow other related articles on the PHP Chinese website!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

DDREASE is a tool for recovering data from file or block devices such as hard drives, SSDs, RAM disks, CDs, DVDs and USB storage devices. It copies data from one block device to another, leaving corrupted data blocks behind and moving only good data blocks. ddreasue is a powerful recovery tool that is fully automated as it does not require any interference during recovery operations. Additionally, thanks to the ddasue map file, it can be stopped and resumed at any time. Other key features of DDREASE are as follows: It does not overwrite recovered data but fills the gaps in case of iterative recovery. However, it can be truncated if the tool is instructed to do so explicitly. Recover data from multiple files or blocks to a single

0.What does this article do? We propose DepthFM: a versatile and fast state-of-the-art generative monocular depth estimation model. In addition to traditional depth estimation tasks, DepthFM also demonstrates state-of-the-art capabilities in downstream tasks such as depth inpainting. DepthFM is efficient and can synthesize depth maps within a few inference steps. Let’s read about this work together ~ 1. Paper information title: DepthFM: FastMonocularDepthEstimationwithFlowMatching Author: MingGui, JohannesS.Fischer, UlrichPrestel, PingchuanMa, Dmytr

The performance of JAX, promoted by Google, has surpassed that of Pytorch and TensorFlow in recent benchmark tests, ranking first in 7 indicators. And the test was not done on the TPU with the best JAX performance. Although among developers, Pytorch is still more popular than Tensorflow. But in the future, perhaps more large models will be trained and run based on the JAX platform. Models Recently, the Keras team benchmarked three backends (TensorFlow, JAX, PyTorch) with the native PyTorch implementation and Keras2 with TensorFlow. First, they select a set of mainstream

Facing lag, slow mobile data connection on iPhone? Typically, the strength of cellular internet on your phone depends on several factors such as region, cellular network type, roaming type, etc. There are some things you can do to get a faster, more reliable cellular Internet connection. Fix 1 – Force Restart iPhone Sometimes, force restarting your device just resets a lot of things, including the cellular connection. Step 1 – Just press the volume up key once and release. Next, press the Volume Down key and release it again. Step 2 – The next part of the process is to hold the button on the right side. Let the iPhone finish restarting. Enable cellular data and check network speed. Check again Fix 2 – Change data mode While 5G offers better network speeds, it works better when the signal is weaker

The latest video of Tesla's robot Optimus is released, and it can already work in the factory. At normal speed, it sorts batteries (Tesla's 4680 batteries) like this: The official also released what it looks like at 20x speed - on a small "workstation", picking and picking and picking: This time it is released One of the highlights of the video is that Optimus completes this work in the factory, completely autonomously, without human intervention throughout the process. And from the perspective of Optimus, it can also pick up and place the crooked battery, focusing on automatic error correction: Regarding Optimus's hand, NVIDIA scientist Jim Fan gave a high evaluation: Optimus's hand is the world's five-fingered robot. One of the most dexterous. Its hands are not only tactile

On Douyin, users can not only share their life details and talents, but also interact with other users. In this process, sometimes we need to send files to other users, such as pictures, videos, etc. So, how to send files to others on Douyin? 1. How to send files to others on Douyin? 1. Open Douyin and enter the chat interface where you want to send files. 2. Click the "+" sign in the chat interface and select "File". 3. In the file options, you can choose to send pictures, videos, audio and other files. After selecting the file you want to send, click "Send". 4. Wait for the other party to accept your file. Once the other party accepts it, the file will be transferred successfully. 2. How to delete files sent to others on Douyin? 1. Open Douyin and enter the text you sent.

I cry to death. The world is madly building big models. The data on the Internet is not enough. It is not enough at all. The training model looks like "The Hunger Games", and AI researchers around the world are worrying about how to feed these data voracious eaters. This problem is particularly prominent in multi-modal tasks. At a time when nothing could be done, a start-up team from the Department of Renmin University of China used its own new model to become the first in China to make "model-generated data feed itself" a reality. Moreover, it is a two-pronged approach on the understanding side and the generation side. Both sides can generate high-quality, multi-modal new data and provide data feedback to the model itself. What is a model? Awaker 1.0, a large multi-modal model that just appeared on the Zhongguancun Forum. Who is the team? Sophon engine. Founded by Gao Yizhao, a doctoral student at Renmin University’s Hillhouse School of Artificial Intelligence.

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects
