Solution to prevent repeated Ajax requests
This article mainly introduces the solution to prevent repeated sending of Ajax requests. Interested friends can refer to it
There are multiple buttons on the page. Click the button to go to the server asynchronously. Read the data and then display the data on the front end. The page requested by each button click is the same, but the request parameters are different, so the returned content is different. When multiple buttons are clicked continuously, multiple asynchronous requests will be issued. Then according to the speed of the request return (because different button parameters are different and the return content is different, there will be speed), the data will be displayed in sequence, then a button clicked first will appear, because the amount of data he requested is relatively large. , causing the data to be displayed later.
1. Problem Solving
There are two ways to solve this problem:
1 .When multiple requests are made continuously and the requested URL addresses are the same. Abandon all previous requests and only execute the last request.
2. When multiple requests are made in succession and the requested url addresses are the same. Abandon all subsequent requests and only execute the first request.
2. Solution
1. Set the async of the ajax request to false
$.ajax({ async: false, type : "POST", url : defaultPostData.url, dataType : 'json', success : function(data) { } });
async
##Type: Boolean
Default value: true. By default, all requests are asynchronous. If you need to send synchronous requests, set this option to false.
Note that synchronous requests will lock the browser, and other user operations must wait for the request to be completed before they can be executed.
2. Use jquery ajaxPrefilter to interrupt the request
Because the first option is just one This curve-based approach to saving the country actually fails to truly solve the above problems. Therefore, it is recommended to use this method.var pendingRequests = {}; $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { var key = options.url; console.log(key); if (!pendingRequests[key]) { pendingRequests[key] = jqXHR; }else{ //jqXHR.abort(); //放弃后触发的提交 pendingRequests[key].abort(); // 放弃先触发的提交 } var complete = options.complete; options.complete = function(jqXHR, textStatus) { pendingRequests[key] = null; if ($.isFunction(complete)) { complete.apply(this, arguments); } }; });
options are the requested options
originalOptions values are as Provides unmodified options to the Ajax method, therefore, there are no default values in the ajaxSettings settings
jqXHR is the requested jqXHR object
Limitations: Only prevents jquery ajax requests from the frontend. Does not work for non-jquery ajax requests. Because the ajaxPreFilter function of jquery is used, it only works on jquery ajax requests.
After calling abort, jquery will execute the error method and throw the abort exception information. This type of exception can be distinguished using the following methods.var ajax = $.ajax({ 'error':function(jqXHR, textStatus, errorThrown){ if(errorThrown != 'abort'){ //ajax被调用abort后执行的方法 alert('您的ajax方法被停止了'); } } })
3. Demo
Every time the button is clicked, a request will be sent to the backend. The following demo implements multiple clicks on the button and only guarantees the last click. The request can succeed.<button id="button1">button1</button> <button id="button2">button2</button> <button id="button3">button3</button> <script> var pendingRequests = {}; jQuery.ajaxPrefilter(function( options, originalOptions, jqXHR ) { var key = options.url; console.log(key); if (!pendingRequests[key]) { pendingRequests[key] = jqXHR; }else{ //jqXHR.abort(); //放弃后触发的提交 pendingRequests[key].abort(); // 放弃先触发的提交 } var complete = options.complete; options.complete = function(jqXHR, textStatus) { pendingRequests[key] = null; if (jQuery.isFunction(complete)) { complete.apply(this, arguments); } }; }); <!-- 异步加载应用列表开始 --> $("#button1").live("click", function() { $.ajax('config/ajax/appinfoListFetcher.json', { type:'POST', data: {param1:value1, param2:value2, }, success: function(res){ //后端数据回写到页面中 }, error:function(jqXHR, textStatus, errorThrown){ if(errorThrown != 'abort'){ //ajax被调用abort后执行的方法 alert('应用加载失败!'); } } }); <!-- 异步加载应用列表结束 --> }); </script>
Ajax transfers JSON example code
ajax uses json to realize data transmission
Spring MVC front-end and back-end 5 ajax interaction methods
The above is the detailed content of Solution to prevent repeated Ajax requests. 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

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.

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to let others know that you have arrived at your destination. Telling others that you have arrived at your destination safely is the most common way of "checking in" and it is easy to operate. Here are the steps to set up before you’re ready to embark on the next leg of your journey. Open a message and start a conversation with the person you want to send a check-in to. Click the plus (+) icon next to the message field. Click Check-in. Click Edit at the bottom of the prompt. Enter the destination you want to go to. Select "Done" in the upper right corner and send "Check-in." "When entering your destination, you can choose different modes of travel depending on your needs, whether that's by car, public transport or walking. Make sure you choose the device you're using correctly so your device can accurately estimate how long it will take to get to your destination. This allows you to better plan your trip and get you to your destination more conveniently.

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.
