JSON and AJAX learning

JSON and AJAX learning

1、Json

1.1, what is Json

  • JSON (JavaScript Object Notation) is a lightweight data exchange format.
  • It is easy to read and write. It is also easy to parse and generate by machine. JSON uses a completely language-independent text format.
  • json is a lightweight data exchange format.
  • Lightweight refers to comparison with xml. Data exchange refers to the transfer format of business data between the client and the server.

1.2. The use of JSON in JavaScript.

  • json is composed of key-value pairs and is surrounded by curly braces (curly braces).
  • Each key is enclosed in quotation marks, the key and value are separated by a colon , and multiple key-value pairs are separated by commas .
var json = {
    
    
"key1":12,
"key2":"abc",
"key3":true,
"key4":[11,"arr",false],
"key5":{
    
    
"key5_1" : 551, 
"key5_2" : "key5_2_value"
},
"key6":[{
    
    
"key6_1_1":6611,
"key6_1_2":"key6_1_2_value"
},{
    
    
"key6_2_1":6621,
"key6_2_2":"key6_2_2_value"
}]
};
  • json itself is an object.
  • The key in json can be understood as an attribute in the object.
  • The key access in json is the same as accessing the properties of the object: json object.key

1.2.1 Two methods commonly used in json

  • JSON.stringify() converts json objects into json strings
  • JSON.parse() converts json string into json object (JavaScript object)
var jsonstr = JSON.stringify({
    
    "a":"Hello","b":"world"});
//结果是 '{a: 'Hello', b: 'World'}'

var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//结果是 {a: 'Hello', b: 'World'}

1.3, the use of Json in java

1.3.1, use gson to parse json

  • Gson is a Java class library provided by Google for mapping between Java objects and JSON data.

  • You can convert a JSON string into a Java object, and vice versa.

  • Gson provides fromJson() and toJson() two methods directly used for parsing and generation

  • fromJson implements deserialization

  • toJson implements serialization

Use gson to first import the gson jar package

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
   <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.8.6</version>
   </dependency>

pojo entity class

public class User {
    
    
    private int age;
    private String name;

    public User() {
    
    
    }

    public User(int age, String name) {
    
    
        this.age = age;
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }
}
@Test
public void test1(){
    
    
    User user = new Person(16,"小明");
    // 创建 Gson 对象实例
    Gson gson = new Gson();
    // toJson 方法可以把 java 对象转换成为 json 字符串
    String userJsonString = gson.toJson(user);
    System.out.println(userJsonString);// {"age":16,"name":"小明"}
    
    // fromJson 把 json 字符串转换回 Java 对象
    // 第一个参数是 json 字符串
    // 第二个参数是转换回去的 Java 对象类型
    User user = gson.fromJson(userJsonString, user.class);
    System.out.println(user);//User{age=16, name='小明'}
}

List and json conversion

 @Test
    public void test2() {
    
    
        List<User> userList = new ArrayList<User>();
        userList.add(new User(16, "张三"));
        userList.add(new User(18, "李四"));
        Gson gson = new Gson();
        //把 List 转换为 json 字符串
        String userListJsonString = gson.toJson(userList);
        System.out.println(userListJsonString);// //[{"age":16,"name":"张三"},{"age":18,"name":"李四"}]
        System.out.println("==================");
        List<User> list = gson.fromJson(userListJsonString, new TypeToken<List<User>>(){
    
    }.getType());
        System.out.println(list);//[User{age=16, name='张三'}, User{age=18, name='李四'}]
    }

Map and json conversion

@Test
    public void test3(){
    
    
        Map<Integer,User> userMap = new HashMap<Integer, User>();
        userMap.put(1, new User(19, "赵六"));
        userMap.put(2, new User(18, "孙七"));
        Gson gson = new Gson();
        // 把 map 集合转换成为 json 字符串
        String userMapJsonString = gson.toJson(userMap);
        System.out.println(userMapJsonString);//{"1":{"age":19,"name":"赵六"},"2":{"age":18,"name":"孙七"}}
        System.out.println("--------------------------------------------");
        Map<Integer,User> userMap1 = gson.fromJson(userMapJsonString, new
                TypeToken<HashMap<Integer,User>>(){
    
    }.getType());
        System.out.println(userMap1);//{1=User{age=19, name='赵六'}, 2=User{age=18, name='孙七'}}
        User user = userMap1.get(1);
        System.out.println(user);//User{age=19, name='赵六'}
    }

1.3.2, use Jackson to parse json

Import Jackson's dependencies

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>
@Test
public void test04() throws JsonProcessingException {
    
    
        //创建一个jackson的对象映射器,用来解析数据
        ObjectMapper mapper = new ObjectMapper();
    
        //创建一个对象
        User user = new User(19,"王麻子");

        //将我们的对象解析成为json格式

        String str = mapper.writeValueAsString(user);

		System.out.println(str);//{"age":19,"name":"王麻子"}
    }
}

1.3.3, Use FastJson to parse json

Import FastJson's dependencies

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>
  • JSON

    • JSON represents the conversion of JSONObject and JSONArray
  • JSONArray

    • JSONArray represents an array of json objects
  • JSONObject

    • JSONObject stands for json object
  1. The parseObject() method of the JSON class realizes the conversion of json strings into json objects or javabean objects
  2. The toJSONString() method of the JSON class realizes the conversion of json objects into json strings and javabean objects into json strings

You can test it by yourself. It's similar to Jackson gson above.

2、AJAX

2.1, what is AJAX

  • AJAX stands for "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), which is asynchronous JS and XML.
  • Refers to a web development technology for creating interactive web applications. Ajax is a technology in which browsers initiate requests asynchronously through js and partially update pages .
  • Partial update of Ajax request, the browser address bar will not change. Partial update will not discard the content of the original page, that is, get data without refresh
  • AJAX is not a new programming language, but a new way of combining existing standards.

The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and parsing server responses. Ability to obtain new data from the server asynchronously.

Advantages :

  • Can communicate with the server without refreshing the page.
  • Allows you to update part of the page content based on user events.

Exemplary Ajax effect

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Ajax</title>
</head>
<body>
<script type="text/javascript">
    function LoadPage(){
     
     

        var targetUrl =  document.getElementById('url').value;

        console.log(targetUrl);

        // 从输入框中获取地址 动态加载
        document.getElementById("iframePosition").src = targetUrl;
    }

</script>

<div>
    <p>请输入要加载的地址:<span id="currentTime"></span></p>
    <p>
        <input id="url" type="text" value="https://www.baidu.com/"/>
        <!--当点击提交时 调用LoadPage方法 获取要加载的地址-->
        <input type="button" value="提交" onclick="LoadPage()">
    </p>
</div>
<div>
    <h3>加载页面位置:</h3>
    <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>
</body>
</html>

effect

Insert picture description here

2.2, AJAX in jQuery

2.2.1, $.ajax method

  • url represents the requested address

  • type indicates the type of request GET or POST request

  • data indicates that there are two formats of data sent to the server:

    • name=value&name=value
    • {key:value}
  • success The request is successful, the response callback function

  • dataType response data type

    Commonly used data types are text for plain text, xml for xml data, json for json object

2.2.2, get and post requests

  • $.get/post(url, [data], [callback], [type])

  • url: The requested URL address.

  • data: The parameters carried by the request.

  • callback: callback function when loading is successful.

  • type: Set the format of the returned content, xml, html, script, json, text, _default.

Use ajax to realize the user login prompt function

@RequestMapping("/ajax")
public String ajaxTest(String name,String pwd){
    
    

    String msg = "";

    //在数据库中查找数据与前端用户输入的数据比较
    if (name!=null){
    
    
        if ("admin".equals(name)){
    
    //这里将数据写死了 实际上是从数据库中查找
            msg = "OK";
        }else {
    
    
            msg = "用户名输入错误";
        }
    }
    if (pwd!=null){
    
    
        if ("123456".equals(pwd)){
    
    

           msg = "OK";
        }else {
    
    

            msg = "密码输入有误";
        }
    }
    return msg; 
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ajax</title>
    <%--导入jquery库--%>
    <script src="*****"></script>
    <script>
        function name(){
            $.post({
                url:"${pageContext.request.contextPath}/ajax",

                data:{'name':$("#name").val()},

                success:function (data) {

                    if (data.toString()=='OK'){

                        $("#userInfo").css("color","green");

                    }else {

                        $("#userInfo").css("color","red");
                    }
                    $("#userInfo").html(data);
                }
            });
        }
        function password(){
            $.post({
                url:"${pageContext.request.contextPath}/ajax",
                data:{'pwd':$("#pwd").val()},

                success:function (data) {

                    if (data.toString()=='OK'){
                        $("#pwdInfo").css("color","green");
                    }else {
                        $("#pwdInfo").css("color","red");
                    }
                    $("#pwdInfo").html(data);
                }
            });
        }
    </script>
</head>
<body>
<p>
    用户名:<input type="text" id="name" οnblur="name()"/>
    <span id="userInfo"></span>
</p>
<p>
   密码:<input type="text" id="pwd" οnblur="password()"/>
    <span id="pwdInfo"></span>
</p>
</body>
</html>

You can read the information online to learn AJAX and JSON

Recommend learning AJAX and JSON-Learning Video B station: still Silicon Valley AJAX or mad God said java

Thank you all for reading! If there is a mistake in the above, please correct it

Guess you like

Origin blog.csdn.net/qq_44763720/article/details/107932274