What is an Ajax request? AJAX, Asynchronous Javascript And XML, is a web development technique for creating interactive web applications. Ajax is a way for the browser to make requests asynchronously. The technique of partially updating a page. 2. Update the page locally
Implementation of native Ajax requests (Understanding)
<script type="text/javascript"> function ajaxRequest() {var XMLHttpRequest = new XMLHttpRequest(); / / 2, calls the open method to set the request parameters xmlHttpRequest. Open (" GET ", "http://localhost:8080/day17/ajaxServlet? action=javaScriptAjax", true); // 4. Bind onReadyStatechange before send to handle the request. xmlHttpRequest.onreadystatechange = function(){ if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) { Alert (" Response back "); / / alert (" server returned data is: "+ xmlHttpRequest. The responseText); var jsonObj = JSON.parse( xmlHttpRequest.responseText ); // alert(" + jsonobj.id + ", "+ jsonobj.name"); Document.getelementbyid ("div01").innerhtml = "+ jsonobj. id +"; } // call xmlHttprequest.send (); Alert (" This is the code after the request "); } </script>Copy the code
Ajax request $. Ajax method URL request address Type Request method GET or POST Data Request parameters (data sent to the server) support two formats: name= Value&Name =value {attribute name: value}
DataType dataType returned by the server. 1.text returns plain text, 2. XML, or 3.json returns a json object
Case study:
/ / ajax request $(" # ajaxBtn "). Click (function () {$. Ajax ({url: "http://localhost:8080/day17/ajaxServlet", type: "GET", Data :"action=jqueryAjax", success:function(MSG){// You have to have a parameter. This parameter is the data alert(MSG) returned by the server; $(" # MSG "). The HTML (" number is: "+ MSG. Id +", name: "+ MSG. Name); }, dataType:"json" }); });Copy the code
$. Get and $. Post url address requested data Requested data callback Successful callback function type Data type of the response Example:
/ / ajax - get request $(" # getBtn "). Click (function () {$.get (" http://localhost:8080/day17/ajaxServlet ", {action: "jqueryGet" },function(MSG){// MSG request success callback function. $("# MSG ").html(" + msg.id + ", name: "+ msg.name); },"json"); }); // ajax--post request $("#postBtn").click(function(){// Post request $.post (" http://localhost:8080/day17/ajaxServlet ", "action = jqueryPost", function (MSG) {/ / MSG request success callback function. $(" MSG ").html("post request number: "+ msg.id + ", name:" + msg.name); },"json"); });Copy the code
$. GetJSON method url request address Data request parameter callback successful callback
The getJSON request format is always GET request, and the data in response is always JSON format. Case study:
// ajax--getJson request $("#getJSONBtn").click(function() $. GetJSON (" http://localhost:8080/day17/ajaxServlet ", "action = jqueryGetJSON", function (MSG) {$(" # MSG "). The HTML (" getJSON request number is: "> < span style =" max-width: 100%; clear: both; }); });Copy the code
Serialize () Serialize () the serialize() method puts all the items in a form. Both are spliced in the form of string name=value&name=value, saving us a lot of unnecessary work.
$.get, $. Post, and getJSON are all asynchronous requests that use the $.ajax() method directly or indirectly. Case study:
$("#submit").click(function(){// serialize() {name=vlaue&name=value var data = $("#form01").serialize(); alert(data); // When we click this button, we want to concatenate all the form items with the information name=value&name=value, Then sent to the server $. GetJSON (" http://localhost:8080/day17/ajaxServlet ", "action = jquerySerialize &" + data, function (MSG) { $("# MSG ").html("jquerySerialize: "+ msg.id + "," + msg.name "); }); });Copy the code
Example:
<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; Charset =UTF-8"> <title>Insert title here</title> <script type="text/javascript" SRC ="script/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){// Ajax request $("#ajaxBtn").click(function(){$.ajax({url: "AjaxServlet ", // request address error:function(){alert(" request failed "); }, function(data){// call alert(data); }, type:"POST", // Request type dataType:"json", // The data type returned is json object data:{// request parameters action:"jqueryAjax", a:12, date: new Date() } }); }); Click (function(){$.get("ajaxServlet",{action:"jqueryGet", a:12, date:new Date() },function(data){alert(data); },"json" ); }); Click (function(){// Post request $. Post (" ajaxServlet", // request path {// request parameter action:"jqueryPost", A :12, date:new date ()}, function(data){alert(data)}, // successful callback function "text" // return data type); }); $("#getJsonBtn").click(function(){$.getjson (" ajaxServlet", Action :"jqueryGetJSON", a:12, date:new date ()}, function(data){alert(data)} }); $("#submit").click(function(){var data = $("#form01").serialize(); alert(data); }); }); </script> </head> <body> <div> <button ID ="ajaxBtn">$. Ajax request </button> <button ID ="getBtn">$. Get request </button> <button </button> <br/><br/> <br/>< form ID ="form01" > <input name="username" type="text" /><br/> Password: <input name="password" type="password" /><br/> Drop-down list: <select name="single"> <option value="Single">Single</option> <option value="Single2">Single2</option> </select><br/> Drop-down multiple selections: <select name="multiple" multiple="multiple"> <option selected="selected" value="Multiple">Multiple</option> <option Value ="Multiple2">Multiple2</option> <option selected="selected" value="Multiple3">Multiple3</option> </select><br/> check: <input type="checkbox" name="check" value="check1"/> check1 <input type="checkbox" name="check" value="check2" Checked ="checked"/> check2<br/> <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="radio" value="radio2"/> radio2<br/> <input id="submit" type="submit" /> </form> </body> </html>Copy the code
2) The code for AjaxServlet is as follows:
package com.atguigu.servlet; import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.atguigu.gson.GsonTest; import com.google.gson.Gson; public class AjaxServlet extends BaseServlet { private static final long serialVersionUID = 1L; protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out.println (" Ajax request coming a--" + request.getParameter("a")); Random random = new Random(System.currentTimeMillis()); Response.getwriter ().write(new Gson().tojson (new gsontest.person (random.nextint (100), "12312"))); } protected void jqueryAjax(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out. println("jqueryAjax request is coming a--" + Request.getParameter ("a")); Random random = new Random(System.currentTimeMillis()); Response.getwriter ().write(new Gson().tojson (new gsontest.person (random.nextint (100), "12312"))); } protected void jqueryGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out.println ("jqueryGet "+ request.getParameter("a")); IOException {system.out.println ("jqueryGet" + request. Random random = new Random(System.currentTimeMillis()); Response.getwriter ().write(new Gson().tojson (new gsontest.person (random.nextint (100), "12312"))); } protected void jqueryPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out.println ("jqueryPost request "--" + Request.getParameter ("a")); Random random = new Random(System.currentTimeMillis()); Response.getwriter ().write(new Gson().tojson (new gsontest.person (random.nextint (100), "12312"))); } protected void jqueryGetJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {system.out.println ("jqueryGetJSON "a --" + Request.getParameter ("a")); IOException {system.out.println ("jqueryGetJSON "a --" + Request. Random random = new Random(System.currentTimeMillis()); Response.getwriter ().write(new Gson().tojson (new gsontest.person (random.nextint (100), "12312"))); }}Copy the code