The client uses AJAX Asynchronous access

### client uses AJAX asynchronous access

`Ajax` namely" Asynchronous Javascript And XML "(Asynchronous JavaScript and XML), refers to a web development technology to create interactive web applications.

First of all, should refer to `jQuery` file, then call the` $ .ajax provided `jQuery` frame ()` function to issue AJAX requests.

In `$ .ajax ()` function, is a function of the parameters JSON object, a conventional configuration requires access to at least five properties:

- `url`: where to submit the request, the value may be a relative path may be is the absolute path;

- `data`: request parameter, usually the name of the format '= value1 & name = value 2 in the format';

-` type`: request type, usually Post` or `` get`;

- ` dataType`: the server side in response to the data type, which can be `text` /` json` / `xml` , will be determined according to Content type response header;

-` success`: when a successful response (response code is the Http 2xx ) callback function, function parameters are JSON object JSON string conversion server response obtained

    <script type="text/javascript" src="jquery-3.4.0.min.js"></script>
    <script type="text/javascript">
    $("#btn-reg").click(function(){
        $.ajax({
            "url":"user/reg.do",
            "data":"username=" + $("#username").val(),
            "type":"post",
            "dataType":"json",
            "success":function(json) {
                alert("state=" + json.state);
            }
        });
    });
    </script>

 

1. The response body ###

when the client makes a request to the server, the server responds to a character string directly in response to the client, if the request is sent by the client browser, the browser interface on a string to display!

The advantage of using this approach is that: no longer server processing interface, i.e. no need to consider the response request, what should be presented to the client interface, the result of the process is simply a response to the client, for example, with 1 indicating success, with 0 indicating failure, as to how to deal with clients and these results show that the problem does not require server-side concerns, at the same time, it solves the problem of multiple display different clients, such as the PC side, the phone side, the tablet PC end, because of differences in equipment, display should also be different, these problems can be handed over to a different client developers to be processed, in addition, a side benefit is that the server generate traffic consumption will be smaller, because the body of the response of much smaller than a certain length in response to the contents of a page length.

The response body approach is to add `@ ResponseBody` before the method of processing the request to comment:

    @Controller
    @RequestMapping("user")
    public class UserController {
        
        @RequestMapping("reg.do")
        @ResponseBody
        public String reg() {
            return "hello";
        }
    
    }

 

2. The body of the response format ### is

not every response `0` or` 1`, or only a certain number to the client, because the client request, may ask for more results! For example the requesting client object is to obtain certain data, such as information of the user currently logged in and the like.

If you need the server response data to the client, you can not directly attribute to a number of data written directly on a string, for example in response to ` 'Six 2517575" `is not appropriate, clients were difficult or no right from a string into a variety of information required! Therefore, the server response to the client's body should have a certain format, in order to ensure that the client receives this text can split out the necessary information.

For example, you can use XML syntax to organize relevant information:

    <user>
        <name>小六</name>
        <age>25</age>
        <height>175</height>
        <weight>75</weight>
    </user>

 

However, the use of XML, there are some problems:

1. The syntax is relatively complicated, and occupy a larger number of characters;

generate and parse 2. The data is relatively complicated;

at present, the industry is relatively advocate of using JSON format to organize data, E.g:

    {
        "name":"小六",
        "age":25,
        "height":175,
        "weight":75
    }

 

### 3. JSON data format

JSON data format is the default language Javascript direct resolved, because JSON is a data type in Javascript!

JSON data format:

1. Each JSON data is an object, each object should be used to frame `` {};

2. Each object may have multiple attributes, the attribute name is a string format requires quotes to frame, the attribute value may be determined according to the data type is used to frame the quotes, separated by commas each attribute;

3. value of the property may be a series of data, the performance of the array in JSON, requires the use of an array of ` [] `to frame, may be obtained by the length of the array length of an array of attributes can also be combined grammar loop through the array;

JSON mainly used to organize data, and forwarded in the network, when the client receives JSON data, the data itself in fact, is a string, you can use `JSON.parse (str)` convert the data string format into JSON object, of course, that the format of this string is in line with the JSON data format.

4. The data server ### in response to a client JSON format

when the method of processing a request to add the controller `@ ResponseBody` annotation, SpringMVC response frame will be achieved by the converter body` Converter`.

SpringMVC default built some converters for different types of return, if the return value of the method of processing the request type is `String`, is called automatically` StringHttpMessageConverter`, encoding the converter default is `ISO-8859 -1`, therefore, by default it does not support Chinese!

Use `Jackson` framework can solve the problem JSON response data and direct support Chinese! When an item added to the `Jackson` dependent, if the method of processing the request controller Return values ​​are in the range of SpringMVC supported by default (e.g., not` string`), the call directly SpringMVC frame `Jackson` converter in response to the body!

    <!-- jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

When you use `Jackson` framework, you need to enable annotation-driven Spring configuration file:

    <! - annotation-driven -> 
    <MVC: Annotation-Driven />

Specific use can be:

    @RequestMapping("reg.do")
    @ResponseBody
    public User reg() {
        User user = new User();
        user.setName("小六");
        user.setAge(30);
        user.setWeight(80);
        return user;
    }

 

When submitting accessed by the client's browser, you can see the body of the response is:

  {"name":"小刘老师","age":30,"weight":80}

 

And, `Jackson` frame further modified` Response Headers`, the response type to:

 Content-Type: application/json;charset=UTF-8

That is, clients get is JSON formatted string, and support the Chinese!

Typically, each project will create a class for representing a body type of data server response to the client.

    public  class ResponseResult <T> {
         Private Integer State; // state, using a numerical description of the success of the operation by the user or not 
        Private String Message; // message, for describing the operation of a user error when failure reason 
        Private T Data; // data for providing data to the client 
    }

 

Guess you like

Origin www.cnblogs.com/cgy-home/p/11094844.html