Simple application of ajax in jQuary

Simple application of ajax in jQuary

ajax

Introduction:

​Ajax = A synchronous J avascript A nd X ML (asynchronous JavaScript and XML)

Ajax refers to a web development technology for creating interactive, fast and dynamic web applications, which can update some web pages without reloading the entire web page.

Ajax enables web pages to be updated asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a webpage can be updated without reloading the entire webpage.

working principle:

​ The working principle of Ajax is equivalent to adding an intermediate layer (AJAX engine) between the user and the server to make user operations and server responses asynchronous. Not all user requests are submitted to the server. Some data validation and data processing are handed over to the Ajax engine itself, and only when it is determined that new data needs to be read from the server will the Ajax engine submit a request to the server on its behalf.

​Compared with the traditional jsp page directly connected to the servlet to jump and refresh the entire page, ajax can directly connect to the background servlet without refreshing the entire page.

​Using ajax to interact with servlets can reduce the use of small scripts in jsp pages and reduce the coupling between front and back ends.

Traditional way: (ordinary interaction of the browser, that is, the interaction between jsp/html and servlet under normal circumstances)
insert image description here

Ajax mode: (Browser's ajax interaction, that is, using ajax in jsp/html to interact asynchronously with servlets to achieve partial page updates)

insert image description here

It can be seen intuitively from the above figure that ajax is used for interaction, and multiple requests are performed asynchronously without interfering with each other.

The implementation of the ajax( ) method:

$.ajax({ 
	url:请求地址,
	type:"get | post | put | delete " 默认是get, 
	data:请求参数 {"id":"123","pwd":"123456"}, 
	dataType:请求数据类型"html | text | json | xml | script | jsonp ",
    success:function(data,dataTextStatus,jqxhr){ },//请求成功时
    error:function(jqxhr,textStatus,error)//请求失败时 
})

//编写上述代码时,注意ajax中每一项参数需要采用逗号隔开
//url:请求的路径  
//type:发送请求的方式
//data:发送的数据  
//datatype 返回的数据类型
//success:成功时执行的方法  error:失败时执行的方法(要么成功,要么失败,两者必须执行其一)
Among the request method types, we commonly use get and post. The difference between the two is:
  • Similar to the get and post methods in the form submission in the jsp page in the traditional way, when the ajax method uses the get method to send data, the data we transmit to the background can be seen in the console, but the transmitted data cannot be seen in the post method

  • GET is simpler and faster than POST, and works in most cases. However, use a POST request in the following cases:

    Unable to use cached files (update files or databases on the server);

    Send a large amount of data to the server (POST has no data limit);

    POST is more stable and reliable than GET when sending user input that contains unknown characters.

When will enter the error method, there are mainly the following situations:
  1. url error: the url path cannot appear in Chinese, and must be an address that can be jumped to
  2. dataType error: the data type returned by the background is inconsistent with what the front desk needs to receive, or the data returned by the background does not conform to the specification, and it will jump into error. For example, when returning in json format, write {id:1, name: "Zhang San"} (error ), the correct format should be {"id":1,"name":"Zhang San"}
  3. Data error: the data requested by the foreground to the background must be written, even if the data is not sent, {} must be passed, otherwise it will return the xml format and prompt parsererror.data: "{}"; the parameters passed between the foreground and the background Must follow the encoding format supported by ajax, and the parameters cannot contain special characters
  4. async request synchronous asynchronous error: async defaults to true, which supports asynchronous requests. If you want to make a synchronous request (ajax execution and then write an ajax execution), you must set async to false
The get() or post() method loads information through a remote HTTP request (to simplify writing):
//get()方法
$.get(url,data,function(result) { //省略将服务器返回的数据显示到页面的代码 });

//post()方法
$.post(url,data,function(result) { //省略将服务器返回的数据显示到页面的代码 });

//url:请求的路径  
//data:发送的数据  
//function(result){}: success时执行的方法

//上面两种方法默认接受的返回数据类型为text类型
//当我们要接受其他形式的数据时,可直接在function方法后加上要接受的数据类型,例:
$.post(url,data,function(result) { //省略将服务器返回的数据显示到页面的代码 },datatype);

If the data returned by the background is in json format, the object needs to be converted into json in the background, otherwise an error will be reported. Most of the methods in the project still receive data of String type. At this time, it involves using GSON to convert the object into a JSON object of String type, which will not be expanded in detail here.

Finally, a simple example (jsp page) is introduced to realize the background function of imitating Weibo likes:

</head>
<script type="text/javascript" src="js/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $(function (){
            $("#zan").click(function (){
                const uid = ${requestScope.uid};
                const zan = $("#zan").val();
                $.ajax({
                    url:"/GreatAjax",
                    type:"post",
                    data:{"uid":uid,"zan":zan},
                    dataType:"JSON",
                    success:function (result){
                        $("#zan").val(result.zan);
                        $("#ag").html(result.allGreat);
                    },
                    error:function (result){
                    	console.log("出错了出错了");
                    }
                })
            })
        })
    </script>
</head>
<body>
    <form>
        用户编号:<span>${requestScope.uid}</span><br><br>
        用户姓名:<span>${requestScope.uname}</span><br><br>
        <input type="button" value="${requestScope.zan}" id="zan"><br><br>
        总点赞数:<span id="ag">${requestScope.allGreat}</span>
    </form>
</body>
${requestScope.zan}" id="zan"><br><br>
        总点赞数:<span id="ag">${requestScope.allGreat}</span>
    </form>
</body>


Guess you like

Origin blog.csdn.net/xiri_/article/details/109597024