Home Web Front-end JS Tutorial Detailed explanation of synchronization processing of $.ajax() and $.getJson() in jQuery_jquery

Detailed explanation of synchronization processing of $.ajax() and $.getJson() in jQuery_jquery

May 16, 2016 pm 03:45 PM
Synchronize

1. Foreword

Why synchronization is needed? Because sometimes when we register a submit button to submit form data, a series of asynchronous ajax request operations will be performed before the submission action, but the page js code will be executed in order from top to bottom. , if you perform an asynchronous operation during this process, you will not be able to obtain the result returned by the current asynchronous operation, and js will continue to execute the next statement, so we need to synchronize the operation request to obtain the background return data result, and then determine whether the result is consistent before executing. js next statement.

2. Explanation of $.ajax() parameters

url: The address to send the request.

type: The request method (post or get) defaults to get.

timeout: requires a parameter of type Number and sets the request timeout (milliseconds).

async: The default setting is true, all requests are asynchronous requests. Synchronous request, set to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed. -----This is the most important setting factor for synchronization operation

cache: The default is true. If the browser has a cache, the browser’s cached data will be obtained. Setting false will not obtain the cached data

data: Requires parameters of type Object or String, data sent to the server. If it is not a string, it will be automatically converted into a string format

Formula. The get request will be appended to the url. To prevent this automatic conversion, check the processData option. The object must be in key/value format

Formula, for example, {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically be different

Values ​​correspond to the same name. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.

dataType: requires a parameter of String type, the data type expected to be returned by the server. If not specified, JQuery will automatically base the http package on mime

The information returns responseXML or responseText and is passed as a callback function parameter.

The available types are as follows:

xml: Returns an XML document that can be processed with JQuery.

html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.

script: Returns plain text JavaScript code. Results are not cached automatically. Unless cache parameters are set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.

json: Returns JSON data.

jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.

text: Returns a plain text string.

beforeSend: requires a parameter of Function type. You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter.

function(XMLHttpRequest){
This; //The options parameter passed when calling this ajax request
            }

complete: requires a parameter of Function type, a callback function called after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the successful request type.

function(XMLHttpRequest, textStatus){
This; //The options parameter passed when calling this ajax request
          }

success: requires parameters of Function type. The callback function called after the request is successful has two parameters.

(1) Data returned by the server and processed according to the dataType parameter.

(2) A string describing the status.

function(data, textStatus){

//data may be xmlDoc, jsonObj, html, text, etc. this;

//The options parameter passed when calling this ajax request

error: requires a parameter of Function type, a function that is called when the request fails. This function has three parameters, namely XMLHttpRequest object, error message, and captured error object (optional).

The ajax event function is as follows:

function(XMLHttpRequest, textStatus, errorThrown){
//Normally, only one of textStatus and errorThrown contains information
This; //The options parameter passed when calling this ajax request
}

contentType: requires a parameter of String type. When sending information to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

dataFilter: requires parameters of Function type, a function that preprocesses the original data returned by Ajax. Provide two parameters: data and type. data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.

function(data, type){
//Return the processed data
                    return data;
            }

global: is required to be a Boolean type parameter, and the default is true. Indicates whether to trigger the global ajax event. Setting to false will not trigger global ajax events, ajaxStart or ajaxStop can be used to control various ajax events.

ifModified: requires a Boolean type parameter, and the default is false. Only get new data when server data changes. The basis for determining server data changes is the Last-Modified header information. The default value is false, which means header information is ignored.

jsonp: requires parameters of String type, and rewrites the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in a GET or POST request such as "callback=?". For example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

username: is required to be a String type parameter, used to respond to the username of the HTTP access authentication request.

password: requires a String type parameter, which is the password used to respond to the HTTP access authentication request.

processData: requires a Boolean type parameter, and the default is true. By default, the data sent will be converted to an object (not technically a string) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false.

scriptCharset: is required to be a String type parameter. It will be used to force the character set (charset) to be modified only when the dataType is "jsonp" or "script" during the request, and the type is GET. Usually used when the local and remote content encodings are different.

3. $.getJson() synchronization settings

$.getJson() itself is an asynchronous operation method and needs to be set up before it can be synchronized

Add $.ajaxSettings.async = false; (synchronous execution) before execution. After executing your code, return to $.ajaxSettings.async = true in time; (asynchronous execution) otherwise it will affect the code in other places that needs to be executed asynchronously. .

4. Specific operation examples

1. $.ajax()

 //点击新增按钮,新增数据
      $("#btnAdd").click(function () {
        var bool = true;//存储异步请求结果是否通过
        //1、验证优惠额度正确性
        var index = parseInt($("#intGiftMold").val());
        if (index == 1) {
          //满减
          var reg = /^[0-9]+,[0-9]+$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '满减优惠额度格式不正确', 'error');
            return false;
          }
        }
        else if (index == 2) {
          var reg = /^0\.[0-9]+$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '折扣优惠额度格式不正确', 'error');
            return false;
          }
        }
        else if (index == 3) {
          var reg = /^[1-9]+[0-9]$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '指定金额优惠额度格式不正确', 'error');
            return false;
          }
        }
        //2、验证优惠范围正确性
        var index = parseInt($("#intGiftRange").val());
        if (index == 1) { //选择全站
        }
        else if (index == 3) {  //判断商品ID
          $.ajax({
           type: "post",
            url: "Gift_Add.aspx",
           cache: false,
            async: false,  //设置同步了~~~~~~~~~
           dataType: "json",
            data: { "method": "isExistInfoTitle", "intInfoID": $("#intInfoID").val() },
            success: function (data) {
              if (data.result == "false") {
                $.messager.alert('错误提示', '商品ID不存在', 'error');
                bool = false;
               $("#isExistInfoTitle").css({ "display": "" });
              }
              else {
                $("#isExistInfoTitle").css({ "display": "none" });
                bool = true;
              }
            }
          });
        }
          });
        }
if (bool == false) {//如果bool为false才返回,true继续往下走
          return false;  //不能在异步方法里面return,不起作用
        }
        var validate = $("#form").form("validate");
        if (!validate) {//表单验证不通过
          return false;
        }
        //当上面全部验证通过了执行新增操作
        $.messager.confirm('温馨提示', '是否确认添加', function (r) {
          if (r) {
            $.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) {
              $.messager.alert('成功提示', '添加成功', 'info');
            });
          }
        });
      });

Copy after login

2. $.getJson()

 //点击新增按钮,新增数据
      $("#btnAdd").click(function () {
        var bool = true;//存储异步请求结果是否通过
        //1、验证优惠额度正确性
        var index = parseInt($("#intGiftMold").val());
        if (index == 1) {
          //满减
          var reg = /^[0-9]+,[0-9]+$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '满减优惠额度格式不正确', 'error');
            return false;
          }
        }
        else if (index == 2) {
          var reg = /^0\.[0-9]+$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '折扣优惠额度格式不正确', 'error');
            return false;
          }
        }
        else if (index == 3) {
          var reg = /^[1-9]+[0-9]$/;
          if (!reg.test($("#strDiscounts").val())) {
            $.messager.alert('错误提示', '指定金额优惠额度格式不正确', 'error');
            return false;
          }
        }
        //2、验证优惠范围正确性
        var index = parseInt($("#intGiftRange").val());
        if (index == 1) { //选择全站
        }
        else if (index == 3) {  //判断商品ID
           $.ajaxSettings.async = false; //设置getJson同步
          $.getJSON("Gift_Add.aspx", { "method": "isExistInfoTitle", "intInfoID": $("#intInfoID").val() }, function (data) {
            if (data.result == "false") {
              $.messager.alert('错误提示', '商品ID不存在', 'error');
              bool = false;
              $("#isExistInfoTitle").css({ "display": "" });
            }
            else {
              $("#isExistInfoTitle").css({ "display": "none" });
              bool = true;
            }
          });
          $.ajaxSettings.async = true;//设置getJson异步
        }
          });
        }
        if (bool == false) {//如果bool为false才返回,true继续往下走
          return false;  //不能在异步方法里面return,不起作用
        }
        var validate = $("#form").form("validate");
        if (!validate) {//表单验证不通过
          return false;
        }
        //当上面全部验证通过了执行新增操作
        $.messager.confirm('温馨提示', '是否确认添加', function (r) {
          if (r) {
            $.post("Gift_Add.aspx?method=addGift", $("#form").serialize(), function (data) {
              $.messager.alert('成功提示', '添加成功', 'info');
            });
          }
        });
      });
Copy after login

Summary:

$.ajax is the AJAX implementation of the traditional get and post methods
$.getJSON is jsonp (remote data reading) class AJAX implementation
The reason why it is called AJAX-like is that although it is encapsulated in the ajax class of jq, it is actually implemented through the script node

The difference between $.getJSON and $.ajax is:

When sending, $.getJSON will pass a callback function name (jq will give one by default)
When receiving, this callback function will be called
The server side of $.getJSON must append the incoming callback function name before the json data
Because of this, the returned string is no longer json (the format is wrong)
Therefore $.ajax with dataType: "json" attribute will enter the error branch

due to json parsing error
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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 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)

Solve the problem of playing headphones and speakers at the same time in win11 Solve the problem of playing headphones and speakers at the same time in win11 Jan 06, 2024 am 08:50 AM

Generally speaking, we only need to use one of the headphones or speakers at the same time. However, some friends have reported that in the win11 system, they encountered the problem of headphones and speakers sounding at the same time. In fact, we can turn it off in the realtek panel and it will be fine. , let’s take a look below. What should I do if my headphones and speakers sound together in win11? 1. First find and open the "Control Panel" on the desktop. 2. Enter the control panel, find and open "Hardware and Sound" 3. Then find the "Realtek High Definition" with a speaker icon. Audio Manager" 4. Select "Speakers" and click "Rear Panel" to enter the speaker settings. 5. After opening, we can see the device type. If you want to turn off the headphones, uncheck "Headphones".

One or more items in the folder you synced do not match Outlook error One or more items in the folder you synced do not match Outlook error Mar 18, 2024 am 09:46 AM

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

MySql data migration and synchronization: How to achieve MySQL data migration and synchronization between multiple servers MySql data migration and synchronization: How to achieve MySQL data migration and synchronization between multiple servers Jun 15, 2023 pm 07:48 PM

MySQL is a very popular open source relational database management system that is widely used in various web applications, enterprise systems, etc. In modern business application scenarios, most MySQL databases need to be deployed on multiple servers to provide higher availability and performance, which requires MySQL data migration and synchronization. This article will introduce how to implement MySQL data migration and synchronization between multiple servers. 1. MySQL data migration MySQL data migration refers to the data migration in the MySQL server.

Teach you how to synchronize the win10 clipboard with your mobile phone Teach you how to synchronize the win10 clipboard with your mobile phone Jan 06, 2024 am 09:18 AM

A very useful function of win10 clipboard is the cross-device cloud storage function, which is very useful and can help users copy and paste simultaneously on PC devices and mobile devices. The setting method is very simple, just set it on the clipboard in the system. Synchronize win10 clipboard to mobile phone 1. First click Start in the lower left corner to enter settings. 2. Then click "System". 3. Select "Clipboard" on the left. 4. Finally, click Login in "Cross-device synchronization" on the right, and then select your mobile phone.

How to select specific folders to sync in OneDrive in Windows 11 How to select specific folders to sync in OneDrive in Windows 11 Apr 13, 2023 pm 04:22 PM

The OneDrive app on your system stores all your files and folders in the cloud. But sometimes users don't want certain files or folders to be stored and take up OneDrive space that is limited to 5 GB without a subscription. To do this, there is a setting in the OneDrive app that allows users to select files or folders to sync on the cloud. If you are also looking for this, then this article will help you select folders or files to sync in OneDrive on Windows 11. How to select certain folders to sync in OneDrive in Windows 11 Note: Make sure the OneDrive app is connected and synced

How to synchronize Baidu cloud synchronization disk How to synchronize Baidu cloud synchronization disk Feb 23, 2024 pm 01:22 PM

How to synchronize Baidu Cloud Sync Disk? You can select files to synchronize in Baidu Cloud Sync Disk, but most users don’t know how to synchronize Baidu Cloud files. Next is the graphic tutorial of Baidu Cloud Sync Disk synchronization method brought by the editor for users. Interested users come and take a look! How to synchronize Baidu Cloud Sync Disk 1. First enter the computer desktop, right-click the [Baidu Cloud Sync Disk] icon and select [Settings]; 2. Then expand the service window, switch to the [Advanced Settings] page and click [Select Folder]; 3. Finally switch to the page as shown below, check the files that need to be synchronized and click [OK].

Locks and synchronization in Python concurrent programming: keeping your code safe and reliable Locks and synchronization in Python concurrent programming: keeping your code safe and reliable Feb 19, 2024 pm 02:30 PM

Locks and Synchronization in Concurrent Programming In concurrent programming, multiple processes or threads run simultaneously, which can lead to resource contention and inconsistency issues. To solve these problems, locks and synchronization mechanisms are needed to coordinate access to shared resources. Concept of Lock A lock is a mechanism that allows only one thread or process to access a shared resource at a time. When one thread or process acquires a lock, other threads or processes are blocked from accessing the resource until the lock is released. Types of locks There are several types of locks in python: Mutex lock (Mutex): ensures that only one thread or process can access resources at a time. Condition variable: Allows a thread or process to wait for a certain condition and then acquire the lock. Read-write lock: allows multiple threads to read resources at the same time, but only allows one thread to write resources

DingTalk schedule synchronization operation process DingTalk schedule synchronization operation process Mar 29, 2024 pm 05:11 PM

1. Open DingTalk on your mobile phone and first select the avatar in the upper left corner. 2. Click Settings at the bottom of the pop-up page. 3. Then click on the settings on the page. 4. Open the calendar settings on the settings page. 5. Click on it and find the synchronized mobile schedule on the page. . 6. Then turn on the synchronization of mobile phone schedules.

See all articles