Analyze the principle and application method of json and jsonp through examples

  • 2021-08-28 18:52:13
  • OfStack

1. Introduction of json and jsonp

In ajax, JSON is used to solve the problem of data exchange, while JSONP is used to realize cross-domain.

Note: Cross-domain can also be solved by server-side proxy;

Understanding: JSON is a data exchange format, while JSONP is an unofficial cross-domain data exchange protocol created by the ingenuity of developers.

2. JSON: It is a text-based data exchange method, or data description format. Whether to choose it must first pay attention to its advantages.

Advantages of JSON:

1) Based on plain text, cross-platform transmission is extremely simple; 2) Javascript native support, background language almost all support; 3) Lightweight data format, which occupies a very small number of characters and is especially suitable for Internet transmission; 4) The readability is strong, although it is not as clear as XML, but it is easy to identify after reasonable indentation in turn; 5) Easy to write and parse, provided you know the data structure;

The format or rule of JSON:

JSON can describe the data structure in a very simple way, and it can do everything XML can do, so the two are completely equal in terms of cross-platform.

1) JSON has only two types of data type descriptors, curly braces {} and square brackets [], and the rest of the English colons: mappers, commas, delimiters, and double quotation marks "" are definers. 2) Braces {} are used to describe a set of "different types of unordered sets of key-value pairs" (each key-value pair can be understood as an attribute description of OOP), and square brackets [] are used to describe a set of "same type of ordered data sets" (which can correspond to an array of OOP). 3) If there are multiple sub-items in the above two sets, they are separated by English commas. 4) The key-value pair is separated by English colon:, and it is recommended that all key names be appended with English double quotation marks "" to facilitate the parsing of different languages. 5) The commonly used data types in JSON are nothing more than string, number, Boolean, date and null. The string must be enclosed by double quotation marks, and the rest are not used. The date type is quite special, so it will not be described here.

It is only suggested that if the client does not have the function requirement of sorting by date, it is good to pass the date and time directly as a string, which can save a lot of trouble.


 Show 1 : {}  Used to describe 1 Group "different types of unordered key-value pair collection" 
    var person = {
      "Name": "Bob",
      "Age": 32,
      "Company": "IBM",
      "Engineer": true
    }
   Show 2 : []  Used to describe 1 Group "Ordered data sets of the same type" 
    var members = [
      {
        "Name": "Bob",
        "Age": 32,
        "Company": "IBM",
        "Engineer": true
      },
      {
        "Name": "John",
        "Age": 20,
        "Company": "Oracle",
        "Engineer": false
      },
      {
        "Name": "Henry",
        "Age": 45,
        "Company": "Microsoft",
        "Engineer": false
      }
    ]
    // Read which John Company name of 
    var johnsCompany = members[1].Company;
  
   Show 3 : {} Included in the [] Use 
    var conference = {
      "Conference": "Future Marketing",
      "Date": "2012-6-1",
      "Address": "Beijing",
      "Members":
      [
        {
          "Name": "Bob",
          "Age": 32,
          "Company": "IBM",
          "Engineer": true
        },
        {
          "Name": "John",
          "Age": 20,
          "Company": "Oracle",
          "Engineer": false
        },
        {
          "Name": "Henry",
          "Age": 45,
          "Company": "Microsoft",
          "Engineer": false
        }
      ]
    }
  
    //  Read attendees Henry Engineer or not 
    var henryIsAnEngineer = conference.Members[2].Engineer;

3. What is JSONP

JSONP (JSON with Padding) is a "usage mode" of the data format JSON, which allows web pages to request data from other domains. Because of the homology policy, 1 generally, a web page located at server1.example. com cannot communicate with a server that is not server1.example. com, while HTML's < script > Element is one exception. Utilization < script > Element, Web pages can get dynamically generated JSON data from other sources, and this usage pattern is called JSONP. The data captured by JSONP is not JSON, but arbitrary JavaScript, which is executed by JavaScript literal translator instead of parsed by JSON parser.

3.1 Principle of JSOPN cross-domain: src attribute of script tag supports cross-domain; Its basic idea is that the web page can be added by adding 1 < script > Element to request JSON data from the server, which is not restricted by the homology policy; After receiving the request, the server sends the data back in a callback function with a specified name.

3.2 JSOP contains two parts: callback function and data. Callback function is a function that should be called when the response arrives, and 1 is generally added through query string; The data is the JSON data passed into the callback function, specifically, an JSON object that can be accessed directly.

3.3 Disadvantages of JSONP:

1) Only GET can be realized without POST;

2) Code loaded from other domains may not be safe; It is difficult to determine whether the JSONP request failed (XHR has an error event). It is common practice to use a timer to specify the allowed time for the response, and the response is considered to have failed beyond the time limit.

In order to facilitate the client to use the data, an informal transport protocol jsonp is gradually formed. One of the key points of this protocol is to allow the user to pass an callback parameter to the server, and then when the server returns the data, the callback parameter will be used as a function name to wrap the json data, so that the client can customize its own function at will to automatically process the returned data

Show:


function ajaxFun(){
      var strUrl="http://www.b.com/demo/json.txt";
       $.ajax({
        type:"get",
        url:strUrl,
        dataType: 'jsonp',
        jsonp: "callback",// That is passed to the request handler or page to get the jsonp Parameter name of callback function name (1 The general default is :callback)
        jsonpCallback: "flightHandler",// Custom jsonp Callback function name, default to jQuery Automatically generated random function name, which can also be written "?" , jQuery Will automatically process the data for you 
        success: function(data){
          alert(' The information you found: fare ' + data.price + ' Yuan, surplus - Ticket ' + data.tickets + ' Zhang. ');
        },
        error: function(XMLHttpRequest,textStatus,errorThrown){
          alert("error");
          //  Status code 
          console.log(XMLHttpRequest.status);
          //  Status 
          console.log(XMLHttpRequest.readyState);
          //  Error message   
          console.log(textStatus);
         }
      });
    }

Remarks:

Among them, sucess code fragments can also be written, and a callback function can be established separately to call the returned data. Data can be obtained from the following one.

var flightHandler = function (data) {
alert ('Information you found: fare' + data. price + 'yuan, remaining tickets' + data. tickets + '. ');
};

It should be noted that in the ajax cross-domain request (jsonp), the data format returned by the server must be: flightHandler ({"price": "120", "tickets": "20"}); If you direct the json format {"price": "120", "tickets": "20"}, an parser error error will be reported. Notice the semicolon at the end of this function "; ", must be added, otherwise, if there are multiple ajax requests on the same page, and other ajax requests are issued when the data is not returned, parsererror error prompts may appear. This kind of error is very hidden, which is not easy to find during development, and it is easy to expose during concurrent testing.

Server-side code listing:


public String jsonReturn(HttpServletResponse response, String callback, Map<String, Object> jsonMap) {
    if (org.apache.commons.lang.StringUtils.isEmpty(callback)) {
      return appAjaxJson(response, getJson(jsonMap));
    }
    return appAjaxJson(response, callback + "(" + getJson(jsonMap) + ")");
  }

  public String appAjaxJson(HttpServletResponse response, String jsonString) {
    return appAjax(response, jsonString, "text/html");
  }

  public String appAjax(HttpServletResponse response, String content, String type) {
    try {
      response.setContentType(type + ";charset=UTF-8");
      response.setHeader("Access-Control-Allow-Origin", "*");// Indicates support for cross-domain requests 
      //  If IE The browser sets the header information as follows 
      if ("IE".equals(type)) {
        response.addHeader("XDomainRequestAllowed", "1");
      }
      response.setHeader("Pragma", "No-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);
      response.getWriter().write(content);
      response.getWriter().flush();
    } catch (IOException e) {
      this.logException(e);
    }
    return null;
  }

4. JSON. stringify (), JSON. parse (), toString ()

4.1 JSON. stringify (): Converts the entry parameter (JavaScript value) into an JSON string;


 Show 1 : 
  let arr = [1,2,3];
  JSON.stringify(arr);//"[1,2,3]"
  typeof JSON.stringify(arr);//"string"

   Example 2 : 
  // Determine whether the array contains an object 
  let data = [
    {name:'echo'},
    {name:' Listen to the wind is the wind '},
    {name:' Son of Heaven laughs '},
    ],
    val = {name:' Son of Heaven laughs '};
  JSON.stringify(data).indexOf(JSON.stringify(val)) !== -1;//true

  // Judge two arrays / Objects are equal 
  let a = [1,2,3],
    b = [1,2,3];
  JSON.stringify(a) === JSON.stringify(b);//true

4.2 JSON. parse (): Converts an JSON string to an object;

Show:

let string = '[1,2,3]';
console.log(JSON.parse(string))//[1,2,3]
console.log(typeof JSON.parse(string))//object

4.3 JSON. Differences between stringify () and toString ()

let arr = [1,2,3];
JSON.stringify(arr);//'[1,2,3]'
arr.toString();//1,2,3


Related articles: