Home  >  Article  >  How jquery implements Ajax requests

How jquery implements Ajax requests

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-05-26 13:37:288354browse

The jquery method to implement Ajax requests: 1. "$.ajax()" method; 2. "$.post()" method, the code is "$.post(url, data, func, dataType) ;"; 3. "$.get()" method, the code is "$.get(url, data, func, dataType);"; 4. "$.getJSON()" method, etc.

How jquery implements Ajax requests

Operating system for this tutorial: Windows 10 system, jQuery3.6.0 version, Dell G3 computer.

jquery implements Ajax request

Ajax is used for communication between the browser and the server without refreshing the entire page. The server will no longer return the entire page, but It returns part of the data and updates the nodes through JavaScript DOM operations. Data transmission formats include xml, json and other formats, but the most commonly used is json format.
We can use the JavaScript object XMLHttpRequest to implement native Ajax, but this method is more complicated and difficult to write. jQuery has encapsulated Ajax, making it easier to initiate Ajax requests. This article briefly introduces the process of jQuery implementing Ajax:

1. Introduce the jquery.js file in the tag

 <script src="https://code.jquery.com/jquery-3.6.1.js"></script>

2. Several common jQuery Ajax methods

(1)$.ajax()
①url: link address, string Represents
②data: (optional) The data to be sent to the server, both GET and POST, will be automatically converted into the request string format, expressed in the form of Key/value pairs, and will be attached to the request as QueryString In the URL, the format is {A: '...', B: '...'}
③type: "POST" or "GET", request type
④timeout: request timeout, unit is milliseconds, value represents
⑤cache: whether to cache the request result, bool means
⑥contentType: content type, the default is "application/x-www-form-urlencoded"
⑦dataType: the data type of the server response, represented by a string; when filled in as json , there is no need to deserialize the data into json
in the callback function ⑧success: the function called back by the server after the request is successful
⑨error: the function called back by the server after the request fails
⑩complete: called after the request is completed function, whether the request is successful or failed, this function will be called; if the success and error functions are set, the function will be called after them
⑪async: whether to process asynchronously, bool means, the default is true; set this value to After false, JS will not execute downwards, but will wait for the server to return data and complete the corresponding callback function before executing downwards
⑫username: The user name carried in the access authentication request, string representation
⑬password: Returns the password carried in the authentication request, the string represents

 <script type="text/javascript">
        function login1(){
            $.ajax({
                //${pageContext.request.contextPath}用于取后端方法的绝对路径的项目名
                url: "${pageContext.request.contextPath}/user/returnJson",
                type: "GET",
                data:'{name: 'James'}', //必须是字符串格式
                contentType:"application/json", //指定内容格式
                dataType:json,
                success: function(data) {  //括号里的data是服务器返回的数据
                    console.log(data);
                    document.getElementById("myDiv").innerText=data["name"];
                }
            });
        }
    </script>
<script>
    $('#btn1').click(function () {
        $.ajax({
            type:"post",	//提交方式
            url:'${pageContext.request.contextPath}/JSONServlet',
            data:{
                bookname:  $("#bookname").val()//val() 方法返回或设置被选元素的值。
            },
            dataType: "json",   	//返回数据的格式
            success:function (responseData) {
                var html = "";
                $('#dataTable tr:not(:first)').remove(); //删除第一行之外的所有行
                // $('#dataTable > tbody > tr').remove();   // 删除所有行,表头会被删除
                console.log(responseData);
                for (var i = 0; i < responseData.length; i++) {
                    html += &#39;<tr>';
                    html += '<td>'+responseData[i].bookid+'</td>'+'<td>'+responseData[i].bookname+'</td>'+'<td>'+responseData[i].price+'</td>'
                    html += '</tr>';
                }
                $('#dataTable').append(html);
            },
        });
    });
</script>

(2)$.post()

Use POST method to execute Ajax request from the server Download Data.
Format: $.post(url, data, func, dataType);
Optional parameters:
①url: link address, string representation
②data: data that needs to be sent to the server, in the format {A: '…', B: '…'}
③func: The function called back by the server after the request is successful; function(data, status, xhr), where data is the data returned by the server, status is the response status, xhr is an XMLHttpRequest object. Personally, you can focus on the data parameter
④dataType: the format of data returned by the server

<script type="text/javascript">
        function login2(){
            $.post(
                "${pageContext.request.contextPath}/user/returnJson",
                 '{name: 'James'}',
                  "application/json",
                 function(data) {
                    console.log(data);
                    document.getElementById("myDiv").innerText=data["name"];
                }
            );
        }
    </script>

(3)$.get()

Use GET method executes Ajax request and loads data from the server.
Form: $.get(url, data, func, dataType);

<script type="text/javascript">
        function login3(){
            $.get(
                "${pageContext.request.contextPath}/user/returnJson",
                function(data) {
                    console.log(data);
                    document.getElementById("myDiv").innerText=data["name"];
                }
            );
        }
    </script>

(4)$.getJSON()

Form: $.getJSON (url, data, func);
Use GET method to execute Ajax request and load JSON format data from the server.

<script type="text/javascript">
        function login4(){
            $.getJSON(
                "${pageContext.request.contextPath}/user/returnJson",
                function(data) {
                    console.log(data);
                    document.getElementById("myDiv").innerText=data["name"];
                }
            );
        }
    </script>

Note: Because the data format returned by the server is determined to be json, this method does not need to specify dataType.

(5)$.load()

Insert the data loaded by the server directly into a node in the specified DOM.
Format: $.load(url, data, func);
If data exists, the request will be sent using POST, and if it does not exist, the request will be sent using GET.

		<div id="myRes"></div>
		function login5() {
            $('#myRes').load(
                "${pageContext.request.contextPath}/user/returnJson",  
                '{name: 'James'}',
                "application/json"
            );
            }

The above is the detailed content of How jquery implements Ajax requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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