Three ways for Jquery to implement AJAX requests
content
Three ways for Jquery to implement AJAX requests
related articles [AJAX Tutorial] JS Native AJAX Request
Introduction
There are many methods of AJAX submission provided in the JQuery script library, but the main methods are $.get(), $.post(), $.ajax(). Among them, $.ajax() is the underlying implementation of the first two methods, which can provide more properties and parameter settings than the first two. If you need advanced settings, it is recommended to use the $.ajax() method.
Project preparation
1. Before using jquery, you need to refer to the jquery library
There are several ways to add jQuery to a web page. You can use the following methods:
- From jquery.com Download the jQuery library
- Load jQuery from a CDN, such as jQuery from Google
Below is the code to load jQuery from CDN.
Code to load jQuery Framework from Google CDN
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js"> </script>
Code to load jQuery Framework from jQuery site (EdgeCast CDN)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"> </script>
Advantages of using a CDN: It reduces the load on the server. It saves bandwidth. The jQuery framework will load faster from these CDN s. The most important benefit is that if the user has visited any site using any of these CDN's jQuery frameworks, it will be cached.
Content Delivery Networks or Content Delivery Networks ( CDN ) is a large-scale distributed server system deployed in multiple data centers on the Internet. The goal of a CDN is to provide content to end users with high availability and performance.
There are 3 popular jQuery CDN: Google, Microsoft, jQuery.
2. Introduce related dependencies
Since this tutorial involves JSON Data parsing, so you need to import the relevant jar package
(If you just want to refer to how to send ajax requests, you can omit the following jar package)
First go to the official download json-lib toolkit json-lib-2.4-jdk15 .jar, the latest version is 2.4,
download link: json-lib-2.4-jdk15.jar
json-lib also requires the following dependencies:
jakarta commons-langx.x
jakarta commons-beanutils x.x.x
jakarta commons-collections x.x.x
jakarta commons-logging x.x.x
ezmorph x.x.x
The download address of each dependency package is as follows.
ezmorph x.x.x:
http://ezmorph.sourceforge.net/
jakarta commons-lang x.x:
http://commons.apache.org/lang/download_lang.cgi
jakarta commons-beanutilsx.x.x:
http://commons.apache.org/beanutils/download_beanutils.cgi
jakarta commons-collections 3.2 :
http://commons.apache.org/collections/download_collections.cgi
jakarta commons-logging 1.1.1 :
http://commons.apache.org/logging/download_logging.cgi
Different versions are different, and there will be version conflicts. The versions in this example are as follows:
$.get() method
The $.get() method loads information via a remote HTTP GET request.
grammar:
$.get(url,data,success(response,status,xhr),dataType)
Notes:
url is required. Specifies which URL to send the request to.
data is optional. Specifies the data to send to the server along with the request.
success(response,status,xhr) is optional. Specifies a function to run when the request is successful.
Additional parameters:
response - contains the result data from the request
status - contains the status of the request
xhr - contains the XMLHttpRequest object
dataType is optional. Specifies the data type of the expected server response.
By default, intelligent judgment (xml, json, script, text, html, etc.) is performed.
Core code:
function Jquery_AJAX_GET() { $.get( 'http://localhost:8080/myWeb/LoginController', { name:$('input[name=name]').val(), password:$('input[name=password]').val() }, //Callback function when the request is successful function(result,status,xhr) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, "json" ) }
$.post() method
The $.post() method loads data from the server via an HTTP POST request.
grammar:
$.post(url,data,success(response,status,xhr),dataType)
Notes:
url is required. Specifies which URL to send the request to.
data is optional. Map or string value. Specifies the data to send to the server along with the request.
success(data, textStatus, jqXHR) optional. Callback function to execute when the request is successful.
Additional parameters:
response - contains the result data from the request
status - contains the status of the request
xhr - contains the XMLHttpRequest object
dataType is optional. Specifies the data type of the expected server response.
Execute intelligent judgment by default (xml, json, script, text, html, etc.)
Core code:
function Jquery_AJAX_POST() { $.post( 'http://localhost:8080/myWeb/LoginController', { name:$('input[name=name]').val(), password:$('input[name=password]').val() }, //Callback function when the request is successful function(result,status,xhr) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, "json" )
$.ajax() method
The ajax() method loads remote data via an HTTP request.
This method is jQuery's underlying AJAX implementation. See $.get, $.post, etc. for easy-to-use high-level implementations.
$.ajax() returns the XMLHttpRequest object it created.
In most cases you don't need to manipulate this function directly, unless you need to manipulate less commonly used options for more flexibility.
In the simplest case, $.ajax() can be used directly without any parameters.
grammar:
$.ajax({name:value, name:value, ... })
Notes:
This parameter specifies one or more name/value pairs for the AJAX request.
The possible names/values are listed in the table below:
name | value/description |
---|---|
async | Boolean value indicating whether the request is processed asynchronously. Default is true. |
beforeSend(xhr) | A function to run before sending a request. |
cache | Boolean value indicating whether the browser caches the requested page. Default is true. |
complete(xhr,status) | A function to run when the request completes (called after the request succeeds or fails, i.e. after the success and error functions). |
contentType | The content type to use when sending data to the server. Default is: "application/x-www-form-urlencoded". |
context | Specify the "this" value for all AJAX related callback functions. |
data | Specifies the data to send to the server. |
dataFilter(data,type) | Functions for processing XMLHttpRequest raw response data. |
dataType | The expected data type of the server response. |
error(xhr,status,error) | A function to run if the request fails. |
global | Boolean value specifying whether to fire the global AJAX event handler for the request. Default is true. |
ifModified | Boolean value specifying whether the request succeeds only if the response has changed since the last request. Default is false. |
jsonp | A string to override the callback function in a jsonp. |
jsonpCallback | Specify the name of the callback function in a jsonp. |
password | Specifies the password used in HTTP access authentication requests. |
processData | Boolean value specifying whether the data sent with the request is converted to a query string. Default is true. |
scriptCharset | Specifies the requested character set. |
success(result,status,xhr) | A function to run when the request is successful. |
timeout | Set the local request timeout in milliseconds. |
traditional | Boolean specifying whether to use the traditional style of parameter serialization. |
type | Specifies the type of request (GET or POST). |
url | Specifies the URL to send the request to. The default is the current page. |
username | Specifies the username to be used in HTTP access authentication requests. |
xhr | Function used to create XMLHttpRequest objects. |
Project demo
1. Create a new login.html file under the Web project to implement user login, the content is as follows:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- From jQuery site loading jQuery Framework the code ( EdgeCast CDN) --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <title>jquery send ajax ask</title> <style> div { width: 240px; height: 100%; margin: 30px auto; } label { margin: 5px auto; height: 22px; line-height: 22px; float: left; } .input { margin: 5px auto; height: 20px; float: right; } #submit { width: 100px; height: 35px; margin: 5px 8px 5px 140px; } </style> </head> <body> <div> <form id="myForm" autocomplete="off" > <label>username:</label> <input class="input" type="text" name="name" placeholder="please enter user name"> <br> <label>password:</label> <input class="input" type="password" name="password" placeholder="Please enter password"> <br> <input id="submit" type="button" value="Log in"> </form> <div id="errorTips" style="text-align: center;font-size: 18px;color: red"></div> </div> </body> </html> <script> $(function() { var $name = $('input[name=name]'); var $password = $('input[name=password]'); $('#submit').click(function() { if($name.val() != '' && $password.val() != '') { //Send a request using $.GET //Jquery_AJAX_GET(); //Send a request using $.POST //Jquery_AJAX_POST(); //Send a request using $.ajax-get //Jquery_AJAX_GET_demo(); //Send a request using $.ajax-post Jquery_AJAX_POST_demo(); } }); //Send a request using $.get() function Jquery_AJAX_GET() { $.get( 'http://localhost:8080/myWeb/LoginController', { name:$('input[name=name]').val(), password:$('input[name=password]').val() }, //Callback function when the request is successful function(result,status,xhr) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, "json" ) } //Send a request using $.post() function Jquery_AJAX_POST() { $.post( 'http://localhost:8080/myWeb/LoginController', { name:$('input[name=name]').val(), password:$('input[name=password]').val() }, //Callback function when the request is successful function(result,status,xhr) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, "json" ) } //Send the request using the $.ajax() get method function Jquery_AJAX_GET_demo() { $.ajax({ type: "get", contentType: "application/json", url: 'http://localhost:8080/myWeb/LoginController', dataType: "json", data: { name:$('input[name=name]').val(), password:$('input[name=password]').val() }, async: "true", success: function(result) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, error: function(e) { alert("error") } }) } //Send the request using the post method of $.ajax() function Jquery_AJAX_POST_demo() { $.ajax({ type: "post", contentType: "application/x-www-form-urlencoded", url: 'http://localhost:8080/myWeb/LoginController', dataType: "json", data: $('#myForm').serialize(), success: function(result) { if(result.status == 'error') { $('#errorTips').text("Username or password is wrong!"); } else if(result.status == 'success') { window.location.href = "library.html"; } }, error: function(e) { alert("error") } }) } }) </script>
2. Write a servlet to receive form data and validate user information, the following is the content of the LoginController.java file:
import net.sf.json.JSONObject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/LoginController") public class LoginController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); //get form data String name = req.getParameter("name"); String password = req.getParameter("password"); //Check if the username and password are correct if("admin".equals(name) && "123456".equals(password)) { JSONObject json = new JSONObject(); json.put("status", "success"); out.print(json); } else { JSONObject json = new JSONObject(); json.put("status", "error"); out.print(json); } } }
3. Write another library.html , jump to this page when the user authentication is passed, the content is as follows:
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- From jQuery site loading jQuery Framework the code ( EdgeCast CDN) --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <title>book list</title> <style> th,td { height: 20px; border: 1px solid #000000; text-align: center; padding: 5px; } </style> </head> <body> <button type="button">View all books</button> <table id="library"> <thead> <tr> <th>book number</th> <th>book title</th> <th>category</th> <th>author</th> <th>publishing house</th> </tr> </thead> <tbody> <tr> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </tbody> </table> </body> </html> <script> $(function () { $('button').click(function () { Jquery_AJAX_GET_demo(); //Jquery_AJAX_POST_demo(); }) //Send a request using $ajax function Jquery_AJAX_GET_demo() { $.ajax({ type: "get", contentType: "application/json", url: 'http://localhost:8080/myWeb/SelectController', dataType: "json", data: {}, async: "true", success: function(result) { showLibrary(result); }, error: function(e) { alert("error") } }) } function Jquery_AJAX_POST_demo() { $.ajax({ type: "post", contentType: "application/json", url: 'http://localhost:8080/myWeb/SelectController', dataType: "json", data: {}, async: "true", success: function(result) { showLibrary(result); }, error: function(e) { alert("error") } }) } function showLibrary(result) { let temp = ''; //Clear existing table content $('tbody tr').slice(0).remove(); for(var i = 0; i < result.length; i++) { temp += "<tr>" + " <td>" + result[i].book number + "</td>" + " <td>" + result[i].book title + "</td>" + " <td>" + result[i].category + "</td>" + " <td>" + result[i].author + "</td>" + " <td>" + result[i].publishing house + "</td>" + "</tr>" } $('#library tbody').append(temp) } }) </script>
Here, use the library.json file to simulate the data stored in the database, and then use the IO stream to read the library.json file to simulate the data query, and return it to the front end.
4. The content of the SelextController.java file is as follows:
import net.sf.json.JSONArray; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; @WebServlet("/SelectController") public class SelectController extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/json;charset=UTF-8"); PrintWriter out = resp.getWriter(); String books = readJSONFile("E://library.json"); JSONArray bookArray = JSONArray.fromObject(books); out.print(bookArray); } //Read JSON file public String readJSONFile(String Path){ BufferedReader reader = null; String result = ""; try{ FileInputStream fileInputStream = new FileInputStream(Path); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8"); reader = new BufferedReader(inputStreamReader); String tempString = null; while((tempString = reader.readLine()) != null){ result += tempString; } reader.close(); }catch(IOException e){ e.printStackTrace(); }finally{ if(reader != null){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
5. The content of the library.json file is as follows:
[ { "book number": "A0120", "book title": "Zhuangzi", "category": "literature", "author": "Zhuang Zhou", "publishing house": "Jilin University Press" }, { "book number": "A0134", "book title": "Three Hundred Tang Poems", "category": "literature", "author": "Li Ping", "publishing house": "Anhui Science Press" }, { "book number": "B1101", "book title": "History of Western Economics", "category": "Finance", "author": "Mo Zhuqin", "publishing house": "Hainan Publishing House" }, { "book number": "B2213", "book title": "business game", "category": "Finance", "author": "Kong Ying", "publishing house": "Peking University Press" }, { "book number": "C1269", "book title": "data structure", "category": "computer", "author": "Li Gang", "publishing house": "Higher Education Press" } ]