Ajax technology [Detailed explanation of Ajax technology, use of Ajax, Ajax request, detailed explanation of JSON, use of JACKSON] (1) - comprehensive explanation (learning summary --- from entry to deepening)

 

Table of contents

Detailed explanation of Ajax technology

 Use of Ajax

Ajax request

 Detailed explanation of JSON

Use of JACKSON 


Detailed explanation of Ajax technology

Introduction to Ajax

Ajax is "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive, fast and dynamic applications, which can update local data on the page without reloading the entire web page. Ajax enables pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that parts of the page can be updated without reloading the entire page. 

 Use of Ajax

How Ajax Works

 XMLHttpRequest object

XMLHttpRequest is a browser interface object. The API of this object can be called by JavaScript, VBScript and other scripting languages ​​embedded in web browsers, and XML or other data can be sent and received between the browser and the web server through the HTTP protocol. XMLHttpRequest can achieve asynchronous interaction with the server without causing the entire page to refresh, so it has become a core object of Ajax programming.

Ajax usage steps

Create an XMLHttpRequest object

var xhr = new XMLHttpRequest();

Given request method and request address

xhr.open("get","http://www.example.com");

send request

xhr.send()

Get the response data from the server to the client

xhr.onreadystatechange = function(){
    //0:请求未初始化
    //1:服务器连接已建立
    //2:请求已接收
    //3:请求处理中
    //4:请求已完成,且响应已就绪
    if(xhr.readyState == 4 && xhr.status == 200){
        document.getElementById("span").innerHTML=xhr.responseText;
        alert(xhr.responseText);
   }
}

Ajax request

 Steps of a request: As you can see in the above example, the XMLHttpRequest object plays an important role

1 The user sends a request from the UI, and JavaScript calls the XMLHttpRequest object.

2 The HTTP request is sent to the server by the XMLHttpRequest object.

3 The server interacts with the database using JSP, PHP, Servlet, ASP.net, etc.

4 Retrieve data.

5 The server sends XML data or JSON data to the XMLHttpRequest callback function.

6 HTML and CSS data are displayed on the browser.

Get/Post request

 Get and post requests are two request methods in the http protocol.

1. The get request is generally used to request to obtain data, and the post request is generally used to send data to the background, transfer data, and create data;

2. The get request can also be passed to the background, but the passed parameters are displayed in the address bar, which has low security, and the length of the parameters is also limited (2048 characters). The post request puts the passed parameters in the request body. It will not be displayed in the address bar, the security is higher than the get request, and the parameter has no length limit;

3. Refreshing the browser or rolling back the get request has no effect, and the post request will request it again;

4. Get requests can be cached and will be kept in the browser's history, while post requests will not be cached and will not be kept in the browser's history;

5. The get request is usually requested through the url address, and the common post is the form form request

 Get request example

xhr.open("GET", "http://localhost:8080/get.txt?t=" + Math.random(), true);
xhr.open("GET", "http://localhost:8080/get.txt?fname=zhang&lname=san", true);

Post request example

xhr.open("POST","http://localhost:8080/post.txt", true);
xhr.setRequestHeader("Contenttype","application/x-www-form-urlencoded");
xhr.send("fname=zhang&lname=san");

synchronous or asynchronous

Async=true

When using async=true, specify a function to execute when the response is in the ready state in the onreadystatechange event

xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 200) {
      document.getElementById("view").innerHTML = xhr.responseText;
   }                
}
xmlhttp.open("GET","get.txt",true);
xmlhttp.send();

Async = false

We do not recommend using async=false, but for some small requests, it is also possible. JavaScript will wait until the server response is ready before proceeding. If the server is busy or slow, the application hangs or stops.

xmlhttp.open("GET","get.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Ajax server response

status line

xhr.status status code, such as 200, 304, 404, etc.;

response body

Both xhr.responseText and xhr.responseXML represent the response body. To get a response from the server, use the responseText or responseXML properties of the XMLHttpRequest object.

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/xmlTest.xml", true);
xhr.send();
xhr.onreadystatechange = function(){
    if (xhr.readyState === 4 && xhr.status === 200) {
     //解析返回的xml文件
    xmlDoc = xhr.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("ARTIST");
    for (i=0;i<x.length;i++) {
   txt = txt + x[i].childNodes[0].nodeValue + "<br>";
   }
  document.getElementById("view").innerHTML = txt;
}
}

 Detailed explanation of JSON

 Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight string-based data exchange format. Easy to read and write, but also easy to machine parse and generate. JSON is a subset of JavaScript data types.

Why use JSON

For the data transfer method in Ajax before JSON appeared, XML will be used as the main data format to transfer data. Until the emergence of JSON, the use of XML as a data transmission format was gradually abandoned. JSON is smaller, faster, and easier to parse than XML.

Characteristics of the JSON format

Syntax rules for JSON

JSON is a string structure generated according to specific grammar rules.

Braces denote JSON string objects. { }

Attributes and values ​​are separated by colons. {"attribute":"value"}

Attributes are separated by commas. {"property":"value","property":"value",...} Brackets indicate an array. [{"attribute":"value"...},{"attribute":"value"...}]

 JSON string object:

{"userid":1,"username":"admin","sex":"male"}

array:

[{"userid":1,"username":"admin"},
{"userid":2,"username":"zhangsan"}]

Data type of JSON

1. string: String must be enclosed in double quotes.

2. number: numerical value, which is consistent with JavaScript's number.

3. object: the object form of JavaScript, represented by { key:value }, which can be nested.

4. array: Array, JavaScript's Array representation [ value ], can be nested.

5. true/false: Boolean type, the boolean type of JavaScript.

6. Null: Null value, null in JavaScript.

Use of JACKSON 

 There is no built-in API for manipulating JSON-format data in JDK, so a third-party class library is required to use and process JSON-format data. Several commonly used JSON parsing libraries: Gson: A JSON library developed by Google with comprehensive functions. FastJson: A JSON library developed by Alibaba with excellent performance. Jackson: The community is very active and updated very quickly. Known as "the best Json parser"

Jackson profile

Jackson is an API for parsing data in JSON format. It is also the most popular and fastest JSON API. The latest version is 2.13.3. There are 3 jar packages to download: jackson-core-2.13.3.jar (core jar package ) jackson-annotations-2.13.3.jar (provides Json annotation support) jackson-databind-2.13.3.jar (data binding, depends on the first two packages)

Introduce Jackson into the project

 Serialization

Use Jackson to convert java objects into Json data. First, create TestBean.java

public class TestBean {
    //id
    private String id;
   //姓名
    private String name;
    //嵌套对象
    private List<Element> elements;
    public String getId() {
        return id;
   }
    public void setId(String id) {
        this.id = id;
   }
    public String getName() {
        return name;
   }
    public void setName(String name) {
        this.name = name;
   }
    public Elements getElements() {
        return elements;
   }
    public void setElements(Elements elements) {
        this.elements = elements;
   }
}

Create Element.java again

public class Element {
   //年龄
    private Integer age;
   //呢称
    private String ename;
    public Integer getAge() {
        return age;
   }
    public void setAge(Integer age) {
        this.age = age;
   }
    public String getEname() {
        return ename;
   }
    public void setEname(String ename) {
        this.ename = ename;
   }
}

Convert Java objects to Json

Element element = new Element();
element.setAge(23);
element.setEName("itbaizhan");
ObjectMapper objectMapper = new ObjectMapper();
String elementStr = objectMapper.writeValueAsString(element);
System.out.println(elementStr);

The output is as follows

{"age":23,"elName":"itbaizhan"}

deserialization

String str = "{\"id\":1,\"name\":\"zhangsan\",\"elements
\":[{\"age\":22,\"elName\":\"xiaozhang\"},
{\"age\":26,\"elName\":\"xiaosan\"}]}";
ObjectMapper objectMapper = new ObjectMapper();
TestBean testBean = objectMapper.readValue(str,TestBean.class);
System.out.println(testBean.toString());

The output is as follows:

TestBean(id=1, name=haha, elements=
[Element(age=22, elName=xiaozhang),
Element(age=26, elName=xiaosan)])

Common Notes

When this annotation is loaded on the class, fields that do not exist will be ignored.

@JsonIgnoreProperties(ignoreUnknown = true)

Specifies to ignore fields

@JsonIgnoreProperties({ “password”, “secretKey” })

Marked on the annotation, this field will be ignored

@JsonIgnore

Mark on the time field and use the specified rules to format (convert to timestamp by default)

@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd")

Whether to participate in serialization

@JsonInclude(参数)

JsonInclude.Include.NON_EMPTY: The property is empty or null and does not participate in serialization JsonInclude.Include.NON_NULL: The property is null and does not participate in serialization

 Mark on the field, specify the serialized field name

@JsonProperty("firstName")

Customize serialization and deserialization rules for certain types of fields

@JsonDeserialize(using= T extends
JsonDeserializer.class)
@JsonSerialize(using= T extends
JsonSerializer.class)

Jquery's Ajax usage

JQuery provides an encapsulation of Ajax, which makes it easier for us to use Ajax technology. JQuery provides many methods for sending asynchronous requests based on Ajax, such as: $.ajax(), $.get(), $.post(), $.getJSON().

$.ajax()在异步请求中提交数据

In the $.ajax() method, the submitted data is stored through the data attribute, and data in JSON format is supported. Common format data is submitted. In the data attribute, we can specify the data to be submitted in two ways. One is through the structure of name=value&name=value. The other is to specify the submitted data through JavaScript objects. No matter which method is used, the value is obtained according to the name through the request.getParameter method in the Servlet. Specify submission data through JavaScript object

data:{
    userid:100,
    username:"zhangsan"
}

Submit data in JSON format

To submit data in JSON format in $.ajax(), you need to use the post method to submit, and use the JSON.stringify() function to convert the JavaScript object into a string in JSON format. Obtain submitted data in JSON format through character input in the Servlet.

data:JSON.stringify({name:value,name:value......})

Obtain the submitted data through req.getReader().readLine() in the Servlet.

$.ajax()处理响应中的 JSON 格式数据

The $.ajax() method will automatically type the response data according to the value in the dataType attribute. If the response is data in JSON format, then the value of dataType is "JSON", and what we get in the callback function is directly the JavaScript object converted from the JSON string. There is no need to use JSON.parse() to do format conversion processing.

$.get()的使用

The $.get() method is a simplified version of the $.ajax() method for sending asynchronous requests based on the get method.

Syntax $.get(url, function(result))

$.get(url,"name=value&name=value",function(result))

 $.get(url,data,function(result))

$.get(url,
{userid:1,username:"zhangsan",...},function(result))
$.post()的使用

The $.post() method is a simplified version of the $.ajax() method for sending asynchronous requests based on the post method.

Syntax $.post(url, function(result))

$.post(url,"name=value&name=value",function(result))
$.post(url,data,function(result))
$.post(url,
{userid:1,username:"zhangsan",...},function(result))

Use of $.getJSON()

 The $.getJSON() method is the $.ajax() method that sends an asynchronous request based on the get method, and automatically converts the string object in JSON format in the response result to a JavaScript object. When using this method, the returned data must be in JSON format. The $.getJSON() method is used together with resp.setContentType("application/json").

 Syntax $.getJSON(url, function(result))

$.getJSON(url,"name=value&name=value",function(result))

$.getJSON(url,data,function(result))

$.getJSON(url,
{userid:1,username:"zhangsan",...},function(result))

The use of the serialize() method will automatically splice the data in the form form into a name=value&name=value structure.

 grammar

var param = $("form").serialize();

The value of param is: name=value&name=value

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/131647674