Home > Web Front-end > JS Tutorial > Introduction to $.ajax() parameters in jQuery and detailed explanation of asynchronous request operation example codes

Introduction to $.ajax() parameters in jQuery and detailed explanation of asynchronous request operation example codes

伊谢尔伦
Release: 2017-07-21 14:51:06
Original
1242 people have browsed it

$.ajax() parameter explanation

url: The address to send the request.

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

timeout: The requirement is a parameter of type Number, set 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 operations

cache: The default is true. If the browser has a cache, the browser's cached data will be obtained. If it is set to false, why will the cached data not be obtained?

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

. The get request will be appended to the url. To prevent this automatic conversion, view the processData option. The object must be in key/value format. For example, {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically assign the same name to different

values. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.

dataType: Parameters required to be String type, data type expected to be returned by the server. If not specified, JQuery will automatically return responseXML or responseText based on the http package mime

information and pass it as a callback function parameter.

The available types are as follows:

xml: Returns an XML document, which 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: The parameter is required to be 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.

                                                                         

The callback function called (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the successful request type.


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

The callback function called after success 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;

//Passed when calling this ajax request The options parameter

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; //Call The options parameters passed in this ajax request

}

contentType: The parameter is required to be 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
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, 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: The parameter is required to be String type, and the name of the callback function is rewritten 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: The parameter is required to be of String type and is used to respond to the username of the HTTP access authentication request.

password: A parameter of type String is required, which is the password used to respond to the HTTP access authentication request.

processData: requires a Boolean type parameter, the default is true. By default, the data sent will be converted to an object (technically not 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: It is required to be a parameter of String type. 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.

Example:

//点击新增按钮,新增数据
      $("#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

The above is the detailed content of Introduction to $.ajax() parameters in jQuery and detailed explanation of asynchronous request operation example codes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template