JQuery uses $.ajax() to implement asynchronous requests

JQuery encapsulates Ajax operations. In JQuery, the $.ajax() method attribute is the bottom method. The second layer is the load(), $.get() and $.post() methods, and the third layer is $. getScript() and $.getJSON() methods. The following will introduce the use of the lowest $.ajax() method.

JQuery uses $.ajax() to implement asynchronous requests, the key code:

//加载数据钮事件
$("#btnLoad").click(function () {
    //请求参数对象
    var params = {};
    params.userName = "pan_junbiao的博客";
    params.password = "123456";

    //执行Ajax请求
    $.ajax({
        type: "POST",
        url: "/user/getLoginUser",
        async: true,
        dataType: "json",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(params),
        success: function (result) {
            //绑定数据
            $("#td_userId").html(result.userId);
            $("#td_userName").html(result.userName);
            $("#td_blogUrl").html(result.blogUrl);
            $("#td_remark").html(result.remark);
        }
    });
});

[Example] Use JQuery's $.ajax() method to asynchronously request the background controller method to obtain user information.

(1) Create a user information parameter class (UserParam.java) to receive the parameters requested by the front-end.

package com.pjb.model;

/**
 * 用户信息参数类
 * @author pan_junbiao
 **/
public class UserParam
{
    private String userName; //用户名称
    private String password; //用户密码

    //省略getter与setter方法...
}

(2) Create a user information model class (UserModel.java) to save user information and return it to the page.

package com.pjb.model;

/**
 * 用户信息模型类
 * @author pan_junbiao
 **/
public class UserModel
{
    private int userId; //用户ID
    private String userName; //用户名称
    private String blogUrl; //博客地址
    private String remark; //备注信息

    //省略getter与setter方法...
}

(3) Create a controller class and implement a method of obtaining login user information in JSON format.

package com.pjb.controller;

import com.pjb.model.UserModel;
import com.pjb.model.UserParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户信息控制器
 * @author pan_junbiao
 **/
@Controller
@RequestMapping("user")
public class UserController
{
    /**
     * 获取JSON格式的登录用户信息
     */
    @RequestMapping(value = "getLoginUser", method = RequestMethod.POST)
    @ResponseBody
    public UserModel getLoginUser(@RequestBody UserParam userParam)
    {
        UserModel userModel = null;
        //判断登录信息
        if (userParam.getUserName().equals("pan_junbiao的博客") && userParam.getPassword().equals("123456"))
        {
            userModel = new UserModel();
            userModel.setUserId(1);
            userModel.setUserName("pan_junbiao的博客");
            userModel.setBlogUrl("https://blog.csdn.net/pan_junbiao");
            userModel.setRemark("您好,欢迎访问 pan_junbiao的博客");
        }
        //返回结果
        return userModel;
    }
}

(4) Create an HTML display page to display user list information.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
    <meta name="author" content="pan_junbiao的博客">
    <style>
        table { border-collapse: collapse; margin-bottom: 10px}
        table,table tr th, table tr td { border:1px solid #000000; padding: 5px 10px;}
        .txtBox{padding: 3px;width: 300px;font-size: 16px;}
    </style>
</head>
<body>
<div align="center">
    <table>
        <caption>用户信息</caption>
        <tr>
            <th>用户ID:</th>
            <td id="td_userId"></td>
        </tr>
        <tr>
            <th>用户名称:</th>
            <td id="td_userName"></td>
        </tr>
        <tr>
            <th>博客地址:</th>
            <td id="td_blogUrl"></td>
        </tr>
        <tr>
            <th>备注信息:</th>
            <td id="td_remark"></td>
        </tr>
    </table>
    <input type="button" id="btnLoad" value="加载数据"/>
</div>
</body>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
    $(document).ready(function()
    {
        //加载数据钮事件
        $("#btnLoad").click(function () {
            //请求参数对象
            var params = {};
            params.userName = "pan_junbiao的博客";
            params.password = "123456";

            //执行Ajax请求
            $.ajax({
                type: "POST",
                url: "/user/getLoginUser",
                async: true,
                dataType: "json",
                contentType: "application/json; charset=UTF-8",
                data: JSON.stringify(params),
                success: function (result) {
                    //绑定数据
                    $("#td_userId").html(result.userId);
                    $("#td_userName").html(result.userName);
                    $("#td_blogUrl").html(result.blogUrl);
                    $("#td_remark").html(result.remark);
                }
            });
        });
    });
</script>
</html>

Results of the:

 

$.ajax() method commonly used parameter description:

parameter name Types of Description
url String A string containing the URL used to send the request.
async Boolean

async (default: true)

By default, all requests are asynchronous requests (that is, this is set to true by default). If you need to send a synchronization request, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operations. Note that the synchronization request will lock the browser, and other user operations must wait for the completion of the request before they can be executed. Starting from jQuery 1.8, the use of async: false in jqXHR ($.Deferred) is obsolete. You must use the success/error/complete callback options instead of the corresponding jqXHR object methods, such as jqXHR.done() or the outdated jqXHR.success()

beforeSend Function Type: Function( jqXHR jqXHR, PlainObject settings)
Callback function before the request is sent, used to modify the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object before the request is sent, this function is used to set custom HTTP header information, etc. . The jqXHR and the setting object are passed as parameters. This is an Ajax event. Returning false in the beforeSend function will cancel the request. Starting with jQuery 1.5, the beforeSend option will be accessed regardless of the type of request.
cache Boolean cache (default: true, the default is false when the dataType is "script" and "jsonp")
If set to false, the browser will not cache this page. Note: Setting cache to false will work properly in HEAD and GET requests. It works by appending "_={timestamp}" to the GET request parameters. This parameter is not necessary for other requests, except in IE8, when a POST requests a URL that has already been requested with GET.
complete Function Type: Function( jqXHR jqXHR, String textStatus) The
callback function after the request is completed (call after both success and error are requested). This callback function gets 2 parameters: jqXHR (XMLHTTPRequest in jQuery 1.4.x) object and a string describing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). Since jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax event.
contents PlainObject An object paired with "{string/regular expression}", according to the given content type, parse the returned result of the request. (1.5 new)
contentType String contentType (default:'application/x-www-form-urlencoded; charset=UTF-8') The
content encoding type when sending information to the server. The default value is "application/x-www-form-urlencoded; charset=UTF-8", which is suitable for most situations. If you explicitly pass a content type (Content-Type) to $.ajax(), then it must be sent to the server (even if there is no data to send). Data will always be passed to the server using the UTF-8 character set; you must decode it appropriately on the server side.
context Object This object is used to set the context of Ajax related callback functions. By default, this context is the parameter setting object used by an ajax request ($.ajaxSettings merges this setting and passes it to $.ajax). For example, specify a DOM element as the context parameter, so that the context of the complete callback function is set to this DOM element. Just like this:
$.ajax({   url: "test.html",   context: document.body }).done(function() {   $(this).addClass("done"); });




converters PlainObject converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML})
a data type to data type converter object . The value of each converter is a function that returns the converted request result. (New in 1.5)
crossDomain Boolean crossDomain (default: false for same-domain requests, true for cross-domain requests)
If you want to force cross-domain requests (such as JSONP) in the same domain, for example, if you want to redirect the server to another domain, you need to set crossDomain Is true. (1.5 new)
data Object, String 发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后面。查看 processData 选项说明,以禁止此自动转换。对象必须为"{键:值}"格式。如果这个参数是一个数组,jQuery会按照traditional 参数的值, 将自动转化为一个同名的多值查询字符串(查看下面的说明)。注:如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。
dataFilter Function 类型: Function( Object data, String type ) => Object
一个函数被用来处理XMLHttpRequest的原始响应数据。这是一个预过滤功能,净化响应。您应该返回安全数据。提供data和type两个参数:data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。
dataType String dataType (默认: Intelligent Guess (xml, json, script, or html))
预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如XML MIME类型就被识别为XML。在1.4中,JSON就会生成一个JavaScript对象,而script则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:
"xml": 返回 XML 文档,可用 jQuery 处理。.
"html": 返回纯文本 HTML 信息;包含的script标签会在插入dom时执行。
"script": 把响应的结果当作 JavaScript 执行。并将其当作纯文本返回。默认情况下不会通过在URL中附加查询字符串变量 "_=[TIMESTAMP]" 进行自动缓存结果,除非设置了cache参数为true。Note: 在远程请求时(不在同一个域下),所有POST请求都将转为GET请求。(因为将使用DOM的script标签来加载)
"json": 把响应的结果当作 JSON 执行,并返回一个JavaScript对象。在 jQuery 1.4 中,JSON 格式的数据以严格的方式解析,如果格式有错误,jQuery都会被拒绝并抛出一个解析错误的异常。(见json.org的更多信息,正确的JSON格式。)
"jsonp": 以 JSONP 的方式载入 JSON 数据块。会自动在所请求的URL最后添加 "?callback=?"。默认情况下不会通过在URL中附加查询字符串变量 "_=[TIMESTAMP]" 进行自动缓存结果,除非将 cache参数设置为true。
"text": 返回纯文本字符串。
多个空格分割的值:从 jQuery 1.5 开始, jQuery可以内容类型(Content-Type)头收到并转换一个您需要的数据类型。例如,如果你想要一个文本响应为XML处理,使用"text xml"数据类型。您也可以将一个JSONP的请求,以文本形式接受,并用jQuery以XML解析: "jsonp text xml"。同样地可以使用"jsonp xml"简写,首先会尝试从 jsonp 到 xml 的转换,如果转换失败,就先将 jsonp 转换成 text, 然后再由 text 转换成 xml。
error Function 类型: Function( jqXHR jqXHR, String textStatus, String errorThrown )
请求失败时调用此函数。有以下三个参数:jqXHR (在 jQuery 1.4.x前为XMLHttpRequest) 对象、描述发生错误类型的一个字符串 和 捕获的异常对象。如果发生了错误,错误信息(第二个参数)除了得到null之外,还可能是"timeout", "error", "abort" ,和 "parsererror"。 当一个HTTP错误发生时,errorThrown 接收HTTP状态的文本部分,比如: "Not Found"(没有找到) 或者 "Internal Server Error."(服务器内部错误)。 从jQuery 1.5开始, 在error设置可以接受函数组成的数组。每个函数将被依次调用。 注意:此处理程序在跨域脚本和JSONP形式的请求时不被调用。这是一个 Ajax Event。
global Boolean

global (默认: true)
无论怎么样这个请求将触发全局AJAX事件处理程序。默认是true 。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或者 ajaxStop。这可以用来控制各种 Ajax Event。

headers PlainObject headers (默认: {})
一个额外的"{键:值}"对映射到请求一起发送。此设置会在beforeSend 函数调用之前被设置 ;因此,请求头中的设置值,会被beforeSend 函数内的设置覆盖 。 (1.5 新增 )
ifModified Boolean ifModified (默认: false)
只有上次请求响应改变时,才允许请求成功。使用 HTTP 包 Last-Modified 头信息判断。默认值是false,忽略HTTP头信息。在jQuery 1.4中,他也会检查服务器指定的'etag'来确定数据没有被修改过。
isLocal Boolean isLocal (默认: 取决于当前的位置协议)
允许当前环境被认定为“本地”,(如文件系统),即使jQuery默认情况下不会这么做。以下协议目前公认为本地:file, *-extension, and widget。如果isLocal设置需要修改,建议在$.ajaxSetup()方法中这样做一次。 (1.5 新增 )
jsonp String 在一个jsonp请求中重写回调函数的名字。这个值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,比如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。在jQuery 1.5,,设置jsonp选项为false,阻止了jQuery从加入"?callback"字符串的URL或试图使用"=?"转换。在这种情况下,你也应该明确设置jsonpCallback设置。例如, { jsonp: false, jsonpCallback: "callbackName" }
jsonpCallback String, Function 为jsonp请求指定一个回调函数名。这个值将用来取代jQuery自动生成的随机函数名。这主要用来让jQuery生成一个独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存GET请求的时候,指定这个回调函数名。从jQuery 1.5开始,你也可以使用一个函数作为该参数设置,在这种情况下,该函数的返回值就是jsonpCallback的结果。
mimeType String 一个mime类型用来覆盖XHR的 MIME类型。 (1.5 新增 )
password String 用于响应HTTP访问认证请求的密码。
processData Boolean

processData (默认: true)

默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

scriptCharset String 仅适用于当"script"传输使用时(例如,跨域的"jsonp"或 dataType选项为"script" 和 "GET"类型)。请求中使用在script标签上设置charset 属性。通常只在本地和远程的内容编码不同时使用。
statusCode PlainObject statusCode (默认: {})
一组数值的HTTP代码和函数对象,当响应时调用了相应的代码。例如,如果响应状态是404,将触发以下警报:
$.ajax({
  statusCode: {
    404: function() {
      alert("page not found");
    }
  }
});
如果请求成功,状态代码对应的函数作为回调的成功相同的参数;如果在一个错误的结果,他们采取了相同的参数error回调。
success Function 类型: Function( Object data, String textStatus, jqXHR jqXHR )
请求成功后的回调函数。这个函数传递3个参数:从服务器返回的数据,并根据dataType参数进行处理后的数据,一个描述状态的字符串;还有 jqXHR(在jQuery 1.4.x前为XMLHttpRequest) 对象 。在jQuery 1.5, 成功设置可以接受一个函数数组。每个函数将被依次调用。这是一个 Ajax Event
timeout Number 设置请求超时时间(毫秒)。此设置将覆盖$.ajaxSetup() 里的全局设置。 超时周期开始于$.ajax 访问成功的那个时间点;如果几个其他请求都在进步并且浏览器有没有可用的连接,它有可能在被发送前就超时了。在 jQuery 1.4.x 和前面的版本中, 如果请求超时,XMLHttpRequest对象是处于无效状态;访问任何对象的成员可能会抛出一个异常。只有在 Firefox 3.0+,script 和 JSONP请求在超时后不能被取消;该脚本将运行即使超时后到达。
traditional Boolean 如果你想要用传统的方式来序列化数据,那么就设置为true。请参考工具分类下面的jQuery.param 方法.
type String type (默认: 'GET')
请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
username String 于响应HTTP访问认证请求的用户名
xhr Function() xhr (默认: 当可用的ActiveXObject(IE)中,否则为XMLHttpRequest)
回调创建XMLHttpRequest对象。当可用时默认为ActiveXObject(IE)中,否则为XMLHttpRequest。提供覆盖你自己的执行的XMLHttpRequest或增强工厂。
xhrFields PlainObject 一对“文件名-文件值”组成的映射,用于设定原生的 XHR对象。例如,如果需要的话,在进行跨域请求时,你可以用它来设置withCredentials为true。
$.ajax({
   url: a_cross_domain_url,
   xhrFields: {
      withCredentials: true
   }
});
在 jQuery 1.5中, withCredentials属性不会传递给原生的XHR从而对于需要使用此属性的 CORS 请求,则只能忽略这个属性。。出于这个原因,我们建议您使用jQuery1.5.1+,如果您需要使用它。

更多$.ajax() 相关参数:《JQuery官方文档》

 

Guess you like

Origin blog.csdn.net/pan_junbiao/article/details/107728066