Home Web Front-end JS Tutorial jQuery+ajax function implementation

jQuery+ajax function implementation

Apr 24, 2018 pm 03:04 PM
Function accomplish

This time I will bring you the implementation of the jQuery ajax function. What are the precautions for the implementation of the jQuery ajax function. The following is a practical case, let's take a look.

Implementation function

Since the ajax method in jq uses the built-in deferred module, it is an implementation of the Promise mode, and we have not talked about it here, so We will not use this mode.

We only define an ajax method, which can simply get, post, and jsonp requests~~

var ajax = function () {
 // 做一些初始化,定义一些私有函数等
 return function () {
 // ajax主体代码
 }
}()
ajax({
 url: myUrl,
 type: 'get',
 dataType: 'json',
 timeout: 1000,
 success: function (data, status) {
 console.log(data)
 },
 fail: function (err, status) {
 console.log(err)
 }
})
Copy after login

The final function of our ajax method is as shown above, very similar to jq. So what are we waiting for, let’s get started.

Overall idea

Our ajax method needs to pass an object into it. In this object we can define some attributes we want, and we will Various attributes must be initialized

//默认请求参数
 var _options = {
 url: null, // 请求连接
 type: 'GET', // 请求类型
 data: null, // post时请求体
 dataType: 'text', // 返回请求的类型,有text/json两种
 jsonp: 'callback', // jsonp请求的标志,一般不改动
 jsonpCallback: 'jsonpCallback', //jsonp请求的函数名
 async: true, // 是否异步
 cache: true, // 是否缓存
 timeout:null, // 设置请求超时
 contentType: 'application/x-www-form-urlencoded',
 success: null, // 请求成功回调函数
 fail: null // 请求失败回调
 }
Copy after login

Above we have defined a large series of request-related data, and then we start writing the ajax main function. The current ajax method is like this

var ajax = function () {
 //默认请求参数
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // ...
 return function (options) {
  // ...
 }
}()
Copy after login

We You can think about it. When the ajax method passes an object in, do we need to overwrite the attributes on the initialization_options with the attributes we set on the object? It is definitely necessary. Then let’s write a simple inheritance first, as follows:

var ajax = function () {
 //默认请求参数
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 内部使用的继承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // ...
 return function (options) {
 // 没有传参或者没有url,抛出错误
 if( !options || !options.url ) {
  throw('参数错误!');
 }
 // 继承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
  // ...
 }
}()
Copy after login

In this inheritance method, we inherit the initialized _options to options. Why? Because our _options object is not inside the ajax method, we need to use it, but we cannot change it. If we change it, the ajax method will crash next time. Therefore, we set the properties that the configured options object does not have to their initial values.

Next, are we going to send a request? etc! It seems that the jsonp request is not an xhr request. It seems to be implemented by inserting the request URL as the src value of the script tag into the page body. Oh, by the way, let's process the jsonp request first and then start building the code for the xhr request.

var ajax = function () {
 //默认请求参数
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 内部使用的继承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // jsonp处理函数
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用户自己定义了回调函数,就用自己定义的,否则,调用success函数
 window[callbackName] = window[callbackName] || succCallback;
 }
 // ...
 return function (options) {
 // 没有传参或者没有url,抛出错误
 if( !options || !options.url ) {
  throw('参数错误!');
 }
 // 继承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  return _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
 }
  // ...
 }
}()
Copy after login

We have defined a _sendJsonpRequest function. This function receives three parameters. The first is jsonpUrl, the second is the callback function name of jsonp, and the third is the success callback function. We are in this function Create a script element with src as jsonpUrl and insert it into the body. At the same time, determine the callback function (if we define the jsonpCallback function, call it, if not, call the success callback. Generally, we do not define the global jsonpCallback function and pass it success callback to complete the jsonp request).

Okay, after processing the jsonp request, we start processing the xhr request.

var ajax = function () {
 //默认请求参数
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // 内部使用的继承方法
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // jsonp处理函数
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用户自己定义了回调函数,就用自己定义的,否则,调用success函数
 window[callbackName] = window[callbackName] || succCallback;
 }
 // json转化为字符串
 var _param = function(data) {
 var str = '';
 if( !data || _empty(data)) {
  return str;
 }
 for(var key in data) {
  str += key + '='+ data[key]+'&'
 }
 str = str.slice(0,-1);
 return str;
 }
 //判断对象是否为空
 var _empty = function(obj) {
 for(var key in obj) {
  return false;
 }
 return true;
 }
 // ...
 return function (options) {
 // 没有传参或者没有url,抛出错误
 if( !options || !options.url ) {
  throw('参数错误!');
 }
 // 继承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  return _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
 }
  //XMLHttpRequest传参无影响
 var xhr = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
 // get搜索字符串
 var search = '';
 // 将data序列化
 var param= _param(options.data)
 if( options.type === 'GET' ) {
  search = (options.url.indexOf('?') > -1 ? '&' : '?') + param;
  if(!options.cache) {
  search += '&radom='+Math.random();
  }
  param = null;
 }
  // ...
 }
}()
Copy after login

First of all, it is compatible with IE to create xhr objects. XMLHttpRequestConstructorPassing parameters has no effect. Then we define two auxiliary variables: search and param. The former is used for query of get request. String, the latter is used for the send content of the post request. We have defined a _param method to convert the object into the send method parameter mode. As you can see, below we have made a reasonable transition between get and post. Assignment work of search and param. Next we can send a request to write the most exciting content.

The final code is as follows

;
var ajax = function () {
 //默认请求参数
 var _options = {
 url: null,
 type: 'GET',
 data: null,
 dataType: 'text',
 jsonp: 'callback',
 jsonpCallback: 'jsonpCallback',
 async: true,
 cache: true,
 timeout:null,
 contentType: 'application/x-www-form-urlencoded',
 success: null,
 fail: null
 }
 // json转化为字符串
 var _param = function(data) {
 var str = '';
 if( !data || _empty(data)) {
  return str;
 }
 for(var key in data) {
  str += key + '='+ data[key]+'&'
 }
 str = str.slice(0,-1);
 return str;
 }
 //判断对象是否为空
 var _empty = function(obj) {
 for(var key in obj) {
  return false;
 }
 return true;
 }
 var _extend = function(target,options) {
 if( typeof target !== 'object' || typeof options !== 'object' ) {
  return;
 }
 var copy ,clone, name;
 for( name in options ) {
  if(options.hasOwnProperty(name) && !target.hasOwnProperty(name)) {
  target[name] = options[name];
  }
 }
 return target;
 };
 // 自定义text转化json格式
 var parseJSON = function(text) {
 if(typeof text !== 'string') {
  return;
 }
 if( JSON && JSON.parse ) {
  return JSON.parse(text);
 }
 return (new Function('return '+text))();
 }
 // jsonp处理函数
 function _sendJsonpRequest(url,callbackName,succCallback) {
 var script = document.createElement('script');
 script.type="text/javascript";
 script.src=url;
 document.body.appendChild(script);
 // 如果用户自己定义了回调函数,就用自己定义的,否则,调用success函数
 window[callbackName] = window[callbackName] || succCallback;
 }
 return function (options) {
 // 没有传参或者没有url,抛出错误
 if( !options || !options.url ) {
  throw('参数错误!');
 }
 // 继承操作
 options.type = options.type.toUpperCase();
 _extend(options,_options);
 /*jsonp部分,直接返回*/
 if( options.dataType === 'jsonp' ) {
  var jsonpUrl = options.url.indexOf('?') > -1 ? options.url: options.url +
  '?' + options.jsonp+ '=' + options.jsonpCallback;
  _sendJsonpRequest(jsonpUrl,options.jsonpCallback,options.success);
  return;
 }
  //XMLHttpRequest传参无影响
 var xhr = new (window.XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP');
 // get搜索字符串
 var search = '';
 // 将data序列化
 var param= _param(options.data)
 if( options.type === 'GET' ) {
  search = (options.url.indexOf('?') > -1 ? '&' : '?') + param;
  if(!options.cache) {
  search += '&radom='+Math.random();
  }
  param = null;
 }
 xhr.open( options.type, options.url + search, options.async );
 xhr.onreadystatechange = function() {
  if( xhr.readyState == 4 ) {
  if( xhr.status >= 200 && xhr.status < 300 || xhr.status == 304 ) {
   var text = xhr.responseText;
   // json格式转换
   if(options.dataType == 'json') {
    text = parseJSON(text)
   }
   if( typeof options.success === 'function') {
   options.success(text,xhr.status)
   }
  }else {
   if(typeof options.fail === 'function') {
   options.fail('获取失败', 500)
   }
  }
  }
 }
 xhr.setRequestHeader('content-type',options.contentType);
 // get请求时param时null
 xhr.send(param);
 // 如果设置了超时,就定义
 if(typeof options.timeout === 'number') {
  // ie9+
  if( xhr.timeout ) {
  xhr.timeout = options.timeout;
  }else {
  setTimeout(function() {
   xhr.abort();
  },options.timeout)
  }
 }
 }
}()
Copy after login

As you can see, we are very familiar with the xhr code. Here, we need to write a method parseJSON that parses the returned string to form a json format object, similar to jq parseJSON method in , as shown above.

We also need to set the timeout code. If the request timeout is set, we define it as above.

Note: In the above code, due to laziness, the line of setting the request header does not determine whether it is under a post request. You can set it yourself~~~.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

jQuery Ajax Analysis Collection

Native js implements ajax request method

The above is the detailed content of jQuery+ajax function implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between vivox100s and x100: performance comparison and function analysis The difference between vivox100s and x100: performance comparison and function analysis Mar 23, 2024 pm 10:27 PM

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

What exactly is self-media? What are its main features and functions? What exactly is self-media? What are its main features and functions? Mar 21, 2024 pm 08:21 PM

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

PHP Tips: Quickly Implement Return to Previous Page Function PHP Tips: Quickly Implement Return to Previous Page Function Mar 09, 2024 am 08:21 AM

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? What are the functions of Xiaohongshu account management software? How to operate a Xiaohongshu account? Mar 21, 2024 pm 04:16 PM

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

See all articles