Get started with jQuery ajax and get started with jQueryajax
In the previous blog, I wrote about the scenario of returning a json string and a json array during ajax requests. Today, I changed the original ajax to jQuery ajax.
JQuery encapsulates ajax a lot, making it very convenient to use ajax, saving a lot of code.
Let's just look at the code.
Code
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
The background code is the same as the previous Code. It is not listed here. For details, refer to ajax response json string and json array.
Code Description
1. The first step to use jQuery is to introduce the jQuery library. Here I put the jQuery library under the js folder under the project root directory.
<! -- Introduce the jQuery library -->
<Script type = "text/javascript" src = "js/jquery. js"> </script>
2 json string processing method
// Json string processing method function jsonStr () {$. ajax ({url: "jsonStr", dataType: "json", success: function (data) {$ ("# username "). val (data. name); $ ("# id "). val (data. id );}});}
In jQuery, we do not need to go to new XMLHttpRequest (), nor pay attention to compatibility issues between browsers. Here jQuery has helped us solve the problem, and we can use $. ajax for bytes;
In callback functions, the old writing method requires writing
xhr.onreadystatechange = function(data) {if (xhr.readyState == 4 && xhr.status == 200) {
But in jQuery's writing method, a success: function (data) {is enough. Is it much easier?
Attach the old ajax Request Code
Function jsonStr () {/** old-fashioned syntax var xhr = new XMLHttpRequest (); xhr. open ("get", "jsonStr"); xhr. onreadystatechange = function (data) {if (xhr. readyState = 4 & xhr. status = 200) {// convert the json string to the json object var obj = eval ("(" + data.tar get. responseText + ")"); document. getElementById ("username "). value = obj. name; document. getElementById ("id "). value = obj. id ;}}; xhr. send (null); */$. ajax ({url: "jsonStr", dataType: "json", success: function (data) {$ ("# username "). val (data. name); $ ("# id "). val (data. id );}});}