Today’s content

  1. AJAX:
  2. JSON

AJAX:

  1. ASynchronous JavaScript And XML

    1. Asynchronous and synchronous: Client and server communicate with each other on the basis of

      • The client must wait for a response from the server. The client cannot perform other operations while waiting.
      • The client does not need to wait for a response from the server. While the server is processing the request, the client can perform other operations.

      Ajax is a technique for updating parts of a web page without having to reload the entire page. [1] Ajax allows web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that part of a web page can be updated without reloading the entire page. A traditional web page (without Ajax) must reload the entire page if it needs to update its content.

      Improve the user experience

  2. Implementation method:

    1. // Create a core object var XMLHTTP; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”); }

      1. Request methods: GET and POST * GET. Request parameters are concatenated after the URL. The send method is empty parameter * POST. Request parameters are defined in the SEND method. 2. Request URL: 3. Synchronous or asynchronous request: true (asynchronous) or false (synchronous) */ xmlhttp.open("GET","ajaxServlet? username=tom",true); //3. Send the request xmlhttp.send(); Xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: xmlhttp.responsetext: The onReadyStatechange event is raised when the readystate of the XMLHTTP object changes. XMLHTTP. Onreadystatechange = function () {/ / judgment readyState ready state is 4, If (xmlhttp.readyState==4 && xmlhttp.status==200) {// Get the result of the server's responseText = xmlhttp.responseText; alert(responseText); }}Copy the code
    2. JQeury implementation

      1. $.ajax()

        • Syntax: $.ajax({key-value pair});

        Ajax () sends asynchronous requests. Ajax () sends asynchronous requests. Ajax () sends asynchronous requests. Ajax ({url:”ajaxServlet1111″, // Request path type:”POST”, // Request method //data: Data :{“username”:”jack”,”age”:23}, success:function (data) {alert(data); },// Error :function () {alert(” error… },// represents the callback function that will be executed if the request response fails

        DataType :"text"// Set the format of the received response data});Copy the code
      2. $.get() : sends a GET request

        • $.get(url, [data], [callback], [type])
          • Parameters:
            • Url: request path
            • Data: request parameters
            • Callback: callback function
            • Type: indicates the type of the response result
      3. $.post() : Sends a POST request

        • $.post(url, [data], [callback], [type])
          • Parameters:
            • Url: request path
            • Data: request parameters
            • Callback: callback function
            • Type: indicates the type of the response result

JSON:

  1. Person p = new Person(); P. etName (” * * “); p.setAge(23); P. etGender (” male “);

    Var p = {“name”:” zhang SAN “,”age”:23,”gender”:” male “};

    • Json is now mostly used as a syntax for storing and exchanging text information
    • Data transmission
    • JSON is smaller, faster, and easier to parse than XML.
  2. Grammar:

    1. The basic rule
      • Data is in name/value pairs: JSON data is made up of key-value pairs
        • Keys are enclosed in quotation marks (odd or even), or without quotation marks
        • Value type:
          1. Numbers (integer or floating point)
          2. String (in double quotes)
          3. Logical value (true or false)
          4. {“persons”:[{},{}]}
          5. Object (in curly braces) {“address”:{“province” : “shaanxi “…. }}
          6. null
      • Data separated by commas: Multiple key-value pairs are separated by commas
      • Preserve objects in curly braces: use {} to define the JSON format
      • Square brackets hold arrays: []
    2. Get data:
      1. Json object. Key name

      2. Json object [” key name “]

      3. Array object [index]

      4. Var person = {“name”: “zhang SAN “, age: 23, ‘gender’: true};

        Var ps = [{" name ":" zhang ", "age" : 23, "gender" : true}, {" name ":" bill ", "age" : 24, "gender" : true}, {" name ":" detective ", "age" : 25, "gender": false}]; //for in loop /* for(var key in person){// Get all the keys in the person object. "Name" //alert(key + ":" + person.key); alert(key+":"+person[key]); } for (var I = 0; i < ps.length; i++) { var p = ps[i]; for(var key in p){ alert(key+":"+p[key]); }}Copy the code
  3. Conversion between JSON data and Java objects

    • JSON parser:
      • Common parsers: Jsonlib, Gson, Fastjson, Jackson
    1. JSON to A Java object
      1. Import the related JAR packages for Jackson
      2. Create the Jackson core object ObjectMapper
      3. Call the corresponding method of ObjectMapper for the transformation
        1. ReadValue (JSON string data,Class)
    2. Java object conversion JSON
      1. Use steps:
        1. Import the related JAR packages for Jackson
        2. Create the Jackson core object ObjectMapper
        3. Call the corresponding method of ObjectMapper for the transformation
          1. Conversion method:

            • WriteValue (parameter 1, obj): Parameter 1: File: Converts an obj object to a JSON string and saves it to the specified File Writer: converts an OBj object to a JSON string and populates the JSON data into an OutputStream: Convert the OBj object to a JSON string and populate the JSON data into the byte output stream
            • WriteValueAsString (obj): Converts an object to a JSON string
          2. Comments:

            1. @jsonignore: Exclude attributes.
            2. @jsonFormat: The attribute is worth formatting
              • @JsonFormat(pattern = “yyyy-MM-dd”)
          3. Complex Java object conversion

            1. An array List:
            2. Map: The object format is consistent

Case study:

  • Verify that the user name exists
    1. The data that the server responds to, when used by the client, should be used as JSON data format. There are two solutions:
      1. $.get(type): specifies the last parameter type as “json”
      2. Set the MIME type response.setContentType(“application/json; charset=utf-8”);