Novice must know: json, ajax, i8n

1. What is json

 

JSON is a lightweight data exchange format.

Lightweight refers to the comparison with xml.

Data exchange refers to the transfer format of business data between client and server.

1.1.1. Use of JSON in JavaScript:

json consists of key value pairs and is surrounded by curly braces (braces). Each key is enclosed by quotation marks, and the keys and values are separated by colons. Multiple sets of key value pairs are separated by commas.         

// Definition of json
var jsonObj ={
   "key1":12,
   "key2":"abc",
   "key3":true,
   "key4":[11,"arr",false],
   "ley5":{
      "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"
   }]
};

1.1.2. json access

json itself is an object.

The key in json can be understood as an attribute in an object.

The key access in json is the same as the attribute of the access object: json object.Key

alert(jsonObj.key1); // object json is an object
for(var i = 0;i < jsonObj.key4.length;i++){
   alert(jsonObj.key4[i]);
}

1.1.3. Two common methods of json:

json exists in two forms.

One is the formal existence of objects, which we call json objects.

One is in the form of string, which we call json string.

Generally, when we want to operate the data in json, we need the format of json object.

Generally, when we want to exchange data between the client and the server, we use json strings.

        JSON.stringify() converts json objects into json strings

        JSON.parse() converts json strings into json objects

// json object to string
var jsonObjString = JSON.stringify(jsonObj); //Especially like toString of objects in Java
alert(jsonObjString);
// String to json object
var jsonObj2 = JSON.parse(jsonObjString);
alert(jsonObj2);

1.2. Using JSON in java

1.2.1. Transformation between javaBean and json

public class JSONTest {
//    1.2.1. Transformation between javaBean and json
    @Test
    public void test1(){
        Person person = new Person(1,"Page");
        //Create Gosn instance
        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);
        // The toJson method can convert Java objects into Json strings
        System.out.println(personJsonString);
        //Fromjason converts json strings back to Java objects
        //The first parameter is the json string, and the second parameter is the java object type that is returned
        Person person1 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person1);
    }

1.2.2. Conversion of List and json

//    1.2.2. Conversion of List and json
    @Test
    public void test2(){
        List<Person> personList = new ArrayList<>();

        personList.add(new Person(1,"Dora"));
        personList.add(new Person(1,"Bad luck"));

        Gson gson = new Gson();
        // Convert List to json string
        String personListJsonString = gson.toJson(personList);
        System.out.println(personListJsonString);
        // Use the PersonListType class to get the collection
        Object person = gson.fromJson(personListJsonString, new PersonListType().getType());

        System.out.println(person);

    }

1.2.3. Mutual transformation of map and json

//    1.2.3. Mutual transformation of map and json
    @Test
    public void test3(){
        Map<Integer,Person> personMap = new HashMap<>();

        personMap.put(1,new Person(1,"Master Kang braised beef noodles"));
        personMap.put(2,new Person(2,"Old hen noodles"));

        Gson gson = new Gson();

        //Convert the Map set to json string
        String personMapJsonString = gson.toJson(personMap);
        System.out.println(personMapJsonString);

//        Map<Integer,Person> personMap1 = gson.fromJson(personMapJsonString, new PersonMapType().getType());
        //Save creating a class
        Map<Integer,Person> personMap1 = gson.fromJson(personMapJsonString, new TypeToken<HashMap<Integer,Person>>(){}.getType());
        System.out.println(personMap1);
        Person p = personMap1.get(1);
        System.out.println(p);

    }

2. What is AJAX:

AJAX, namely "Asynchronous Javascript And XML", refers to a web page development technology for creating interactive web page applications.

ajax is a technology that browsers send requests asynchronously through js and update pages locally.

The browser address bar will not change when Ajax requests local updates

Partial update will not discard the contents of the original page

Server response:

 

Instances of native Ajax requests:

<!DOCTYPE html PUBLIC "-//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">
         //Here, we use JavaScript language to initiate Ajax requests and access JavaScriptAjax in the server AjaxServlet
         function ajaxRequest() {
//              1. We first need to create XMLHttpRequest
            var xmlhttprequest = new XMLHttpRequest();
//              2. Call the open method to set the request parameters
            xmlhttprequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=JavaScriptAjax",true);
//              3. Call the send method to send the request
            xmlhttprequest.send();
//              4. Bind the onreadystatechange event before the send method to handle the operation after the request is completed.
            xmlhttprequest.onreadystatechange = function () {
               if(xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){

                  var jsonObj = JSON.parse(xmlhttprequest.responseText);

                  //Display the response data on the page
                  document.getElementById("div01").innerHTML = "No.:"+jsonObj.id + ",full name:"+jsonObj.name;
               }
            }
         }
      </script>
   </head>
   <body> 
      <button onclick="ajaxRequest()">ajax request</button>
      <div id="div01">
      </div>
   </body>
</html>

2.3 Ajax requests in jquery

$. ajax method

url indicates the address of the request

Type indicates the type of request GET or POST request

Data indicates the data sent to the server

There are two formats:

I: name=value&name=value

II: {key:value}

success request is successful, the callback function of the response

dataType the data type of the response

Common data types are:

Text means plain text

xml represents xml data

json represents a json object

// ajax request
$("#ajaxBtn").click(function(){
   
   // alert("ajax btn");
   $.ajax({
      url:"http://localhost:8080/16_json_ajax_i18n/AjaxServlet",
      data:"action=jQueryAjax",
      type:"Get",
      success:function(data){
         alert("The data returned by the server is:"+ data)

         var jsonObj = JSON.parse(data);

         $("#msg").html(" Number: "+ jsonObj.id+", name: "+ jsonobj.name");

      },
      dataType:"text"
   });

});

$. get method and $ post method

url requested url address

Data sent by data

Callback successful callback function

Data class returned by type

// ajax--get request
$("#getBtn").click(function(){

   // alert(" get btn ");

   $.get("http://localhost:8080/16_json_ajax_i18n/AjaxServlet","action=jQueryGet",function (data) {
      $("#msg").html(" get number: "+ jsonObj.id+", name: "+ jsonobj.name");
   },"json");
   
});

// ajax--post request
$("#postBtn").click(function(){
   // post request
   // alert("post btn");

   $.post("http://localhost:8080/16_json_ajax_i18n/AjaxServlet","action=jQueryPost",function (data) {
      $("#msg").html(" post number: "+ jsonObj.id+", name: "+ jsonobj.name");
   },"json");

});

$. getJSON method

url requested url address

Data data sent to the server

Callback successful callback function

// ajax--getJson request
$("#getJSONBtn").click(function(){
   // call
   // alert("getJSON btn");

   $.getJSON("http://localhost:8080/16_json_ajax_i18n/AjaxServlet","action=jQueryGetJSON",function(data){
      $("#msg").html(" getJSON number: "+ jsonObj.id+", name: "+ jsonobj.name");
   });

});

Form serialization serialize()

serialize() can get the contents of all form items in the form and splice them in the form of name=value&name=value.

// ajax request
$("#submit").click(function(){
   // Serialize parameters
   // alert("serialize()");

   $("#form01").serialize();

   $.getJSON("http://localhost:8080/16_json_ajax_i18n/AjaxServlet","action=jQuerySerialize&" + $("#form01").serialize(),function (data) {
      $("#msg").html(" jQuerySerialize number: "+ jsonObj.id+", name: "+ jsonobj.name");
   });

});

3.i18n internationalization (understand)

4.2 relevant elements of Internationalization:

 

Tags: Front-end JSON Back-end Ajax

Posted by abhi on Thu, 04 Aug 2022 21:44:51 +0300