The core of Ajax is the JavaScript object XmlHttpRequest. This object was first introduced in Internet Explorer 5 and is a technology that supports asynchronous requests. In short, XmlHttpRequest allows you to use JavaScript to make requests to the server and handle the responses without blocking the user. In this article, we will share with you how to write ajax requests in the most elegant way.
First you need a configuration file
var api = { basePath: 'http://192.168.200.226:58080', pathList: [ { name: 'agentHeartBeat', path:'/api/csta/agent/heartbeat/{{agentId}}', method:'post' }, { name: 'setAgentState', path: '/api/csta/agent/state', method: 'post' }, { name: 'getAgents', path: '/user/agent/{{query}}', method: 'get' } ] }
Then you need a method to generate an interface from the configuration file
function WellApi(Config){ var headers = {}; var Api = function(){}; Api.pt = Api.prototype; var util = { ajax: function(url, method, payload) { return $.ajax({ url: url, type: method || "get", data: JSON.stringify(payload), headers: headers, dataType: "json", contentType: 'application/json; charset=UTF-8' }); }, /** * [render 模板渲染] * 主要用于将 /users/{{userId}} 和{userId: '89898'}转换成/users/89898,和mastache语法差不多, * 当然我们没必要为了这么小的一个功能来引入一个模板库 * query字符串可以当做一个参数传递进来 * 例如: /users/{{query}}和{query:'?name=jisika&sex=1'} * @Author Wdd * @DateTime 2017-03-13T19:42:58+0800 * @param {[type]} tpl [description] * @param {[type]} data [description] * @return {[type]} [description] */ render: function(tpl, data){ var re = /{{([^}]+)?}}/g; var match = ''; while(match = re.exec(tpl)){ tpl = tpl.replace(match[0],data[match[1]]); } return tpl; } }; /** * [setHeader 暴露设置头部信息的方法] * 有些方法需要特定的头部信息,例如登录之后才能获取sesssionId,然后访问所有的接口时,必须携带sessionId * 才可以访问 * @Author Wdd * @DateTime 2017-03-13T10:34:03+0800 * @param {[type]} headers [description] */ Api.pt.setHeader = function(headers){ headers = headers; }; /** * [fire 发送ajax请求,this会绑定到每个接口上] * @Author Wdd * @DateTime 2017-03-13T19:42:13+0800 * @param {[type]} pathParm [description] * @param {[type]} payload [description] * @return {[type]} [description] */ function fire(pathParm, payload){ var url = util.render(this.path, pathParm); return util.ajax(url, this.method, payload); } /** * [for 遍历所有接口] * @Author Wdd * @DateTime 2017-03-13T19:49:33+0800 * @param {[type]} var i [description] * @return {[type]} [description] */ for(var i=0; i <p> </p><h2 id="Try-it-out">Try it out</h2><pre class="brush:php;toolbar:false">nbsp;html> <meta> <title></title> <script></script> <script></script> <script></script> <script> var saas = WellApi(api); saas.agentHeartBeat.fire({agentId: '5001@1011.cc'}) .done(function(res){ console.log('心跳成功'); }) .fail(function(res){ console.log('心跳失败'); }); </script>
Advantages and extensions
[Advantages]: Callback method similar to promise
[Advantages]: Adding an interface only requires adding a configuration file, which is very convenient
[Extension]: I only wrote json for the current ajax contentType , you can expand other data types if you are interested
[Disadvantages]: There is no verification of function parameters
The above content is how to use the most An elegant way to write ajax requests. Hope it helps everyone.
Related recommendations:
php handles ajax requests and ajax cross-domain
javascript implements ajax request steps and usage examples
How to implement the usage of ajax request in jquery
The above is the detailed content of The most elegant way to write ajax requests in jQuery. For more information, please follow other related articles on the PHP Chinese website!

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.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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.

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.