JavaWEB Notes 14 jQuery Sends AJAX and JAVA Background JSON Data

Keywords: Java JQuery JSON Ajax

JavaWEB Notes 14 jQuery Sends AJAX and JAVA background and JSON data

Part One: jQuery Sends AJAX

1.jQuery sends AJAX details:

The main purpose of AJAX is to refresh some requests on the page without reloading the page, and submit the form to the background. There are many ways to send AJAX using jQuery. Now you are introducing jQuery's native AJAX:
GET requests for native AJAX are divided into four steps:

  • 1) Create an asynchronous request object;
  • 2) Open the link to send the request;
  • 3) Send requests;
  • 4) Receive background response;

Native AJAX POST request:
Before sending a POST request, set the request header: setRequestHeader() to add the HTTP header, and then use the send() method to specify the data you want to send
POST request: Submit request parameters, background use key values to compare

AJAX after jQuery encapsulation:
jQuery sends AJAX requests: button s for design:

$('button').click(function(){ $.ajax({ Content is jsonobj }) })

Details: Details of the json object above are:

  • Request method: type:'POST'//GET, etc.
  • Background address of request: url="some.php"
  • Request parameter: data:'name=Jhon&location=London'
  • Callback functions for successful background responses: success: function (respData) {console.log (respData)}, dataType:'json'; //Without datatype, only strings, not objects, are converted
    Where the function is automatically converted to a json object when the background response succeeds
  • In the above parameters, the url can spell the url parameter without writing data when the request mode is GET.If the GET parameter does not want to be spelled, change it to url and write it as a json object key-value pair in the data
  • Failed requests can also add parameters: error handles

2. Other AJAX encapsulations in jQuery:

1) When sending AJAX using jQuery, if AJAX wants to send get requests:

$.get(url,data,callback,Return type:"json")

Where the corresponding callback function can be expanded
2) If AJAX wants to send a POST request:

$.post(url,data,callback,,Return type:"json")

3) Get the json data of the background response directly:

$.getJSON(url,data,callback)

All three methods are more specific and focus on remembering the complete method of AJAX.

3. Cross-domain issues:

1. Cross-domain introduction:

Cross-domain issues refer to inaccessible cross-domain access at request time
Cross-domain issues: Due to the browser's homology policy (for security reasons), there is no cross-domain in nature, browsers are restricted, but servers in general do not
Cross-domain refers specifically to: A site sends AJAX requests to B site internally
Homology: same protocol + same domain name + same port number
Once the server has made a cross-domain interface, it can access the data on the front end

2. Cross-domain Requests and Solutions:

There are three ways jQuery can handle cross-domain issues when sending AJAX:

  • 1) Using JSONP across domains:
    Features: Only GET requests are supported, other requests are not supported
    Principle of cross-domain requests: Some tags are not restricted by the same browser, such as img script link (unless there is an anti-theft chain in the background)
    JSONP uses script for cross-domain purposes: set the corresponding label for filling in the url to script, noting that the function name of the callback function after the response succeeds is followed by & callback=function name
    JSONP response: The corresponding callback function is placed in the server and the corresponding return string is wrapped
  • 2) Mainstream method 1:cors cross-domain:
    How it works: Browsers do not hijack data that comes back from the server, that is, trust the browser
    Set the response.setHeader in the background ("Access-Control-Allow-Origin", "*") to approve all cross-domain requests
  • 3) Mainstream method 2: Agent cross-domain:
    There is no homology policy between the server and the server, so set up a proxy server between the server as a non-cross-domain server for the current request browser

4. jQuery generates jsonp:

JQuery generates jsonp by using jQuery's request template for AJAX before:
1) Reservation

type:"get",url:"..."

2) New

jsonp:"callback" //jQuery automatically generates a callback function, does not need to name itself, etc.

3) Keep the back

success:function(res){ alert(res); }

4) Last

dataType: "jsonp" //Data type of background response

5) Notes:
Background generates the corresponding string when responding;
If you have to set the callback function name:

jsonpCallback: 'haha'

But write the corresponding callback function later on.
The simpler method above: getJSON sends jsonp:

$.getJSON({ url Last callback=?,function(res){alert(res)}})

Part Two: JAVA Background and JSON Data

5. JSON string to JAVA object:

To convert the JSON string submitted by the foreground into a JAVA object, the background creates a new class and encapsulates its member variables with their keys:
Processing string:
1) Remove braces:

str.replaceAll("\\{","");And corresponding"\\}"

2) intercept commas:

String strings = str.split(",");

Then they correspond to different substrings in strings[]
3) Intercept the colon in each subparagraph:

String[] num = s1.split(":")

4) Physical activity converts all the above key pairs

Converting a JAVA object to a JSON string: String

StringBuilder str = new StringBuilder("{");
(str).append("\"").append("name").append("\"").append(":").append(user.getName())

Or simply use the corresponding str1+str2 form to string together

JAVA provides a third-party tool class to complete the conversion of JSON strings and JAVA objects: There are many third-party JSON parsers: Jsonlib, Gson, fastjson, jackson
Here's how to add third-party jar packages, just like the built-in parser in the later framework:
1) Copy third-party jar packages to create a new lib folder under this project directory
2) Right click on lib to add as library

Convert JSON strings into java objects using third-party jar packages:

  • 1) String jsonStr="{...}" defines a class whose member variable name and data type and name are identical to the keys in the json string
  • 2) Call the Jackson method:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonStr, User.class); 

Two parameters: the json string and the bytecode file object in the class you define

  • 3) The difficulty of this method is to construct corresponding hierarchical classes

Matters needing attention:
When data in formats such as "list":["aaa","bbb"] appears in JSON, set the list as a collection when creating a new class:

ArrayList<String> list = User.getlist(); //Press alt+enter to import the package

Nested form of key value: The value corresponding to the key appears as a key-value pair
For class keynames across domains, redesign a class:
If you can create a new Car class: private Car mycar creates a new Car class

Install plug-ins one-click generation:
Right-click on the GsonFormat in Generate to enter the corresponding JSON, then select the corresponding jackson (jack) at the bottom left of the backpoint. The above operations are edited on the design of the outermost class. The difficulty in installing the plug-in method is to install the corresponding plug-in

6. JAVA objects are converted to JSON strings:

Simple Method (Physical Work): String
Call the method in jackson:

ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user); 
//user is the outermost class corresponding to the hierarchical relationship

When collections or other classes occur in hierarchical nesting: instantiate all the classes that occur, and then use the above generation rules, note that generating double-chain collections: Generating the corresponding HashMap

Save the generated JSON string to a file:

objectMapper.writeValue(new File("file name"),map)

Which fields in the object do not want to be converted when converting:
Use annotations to control: @JsonIgnore ignores a field and does not want to be converted to JSON

About date fields: Format the returned millisecond values into years, months, days, minutes, seconds
Use annotations to control: @JsonFormat(pattern = "yyy-MM-dd HH:mm:ss")
Set the corresponding time zone: Add timezone = GMT+8 at the end of the brackets above

Ignore null values when converting:
Add a comment: @JsonInclude(JsonInclude.Include.NON_NULL) Do not rotate if null

The names in the corresponding strings are dynamically changed during conversion:
Use the comment: @JsonProperty("Changed Name")

jQuery case: Mobile phone number attribution inquiry:

Case Requirements:
Design a mobile phone number home query page, using CSS, jQuery encapsulated AJAX, combined with events in jQuery or native dom events for JS dynamic operation page
Source code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Mobile Phone Number Ownership Professional Query</title>
    <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
    <style type="text/css">
        *{
            list-style: none;
        }
        #topElem{
            margin-top: 20px;
            width: 60%;
            margin-left: 20%;
        }
        #top{
            font-size: 40px;
            width: 100%;
            height: 50px;
            line-height: 50px;
            text-align: center;
            margin-left: -10px;
        }
        #haomaduan{
            font-size: 20px;
            margin-top: 25px;
            margin-left: 10px;
        }
        #srch{
            border: gray solid 1px;
            width: 75%;
            height: 36px;
            margin-top: 20px;
        }
        .btn{
            width: 100px;
            height: 41px;
            border: none;
            background-color: #3fac24;
            color: white;
            font-size: 20px;
            position: absolute;
            left: 65%;
            top: 141px;
        }
        .btn:hover{
            cursor: pointer;
        }
        #bodypart{
            position: relative;
            width: 66%;
            margin-left: 17%;
            margin-top: 30px;
        }
        #chaxjg{
            position: absolute;
            width: 92%;
            height: 45px;
            background-color: rgba(154, 150, 143, 0.56);
            border: gray solid 1px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
        }
        #number{
            position: absolute;
            top: 47px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #number_json{
            position: absolute;
            top: 47px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityinfo{
            position: absolute;
            top: 91px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityinfo_json{
            position: absolute;
            top: 91px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #companyinfo{
            position: absolute;
            top: 135px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #companyinfo_json{
            position: absolute;
            top: 135px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityblock{
            position: absolute;
            top: 179px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityblock_json{
            position: absolute;
            top: 179px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #postcode{
            position: absolute;
            top: 223px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #postcode_json{
            position: absolute;
            top: 223px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #moreinfo{
            position: absolute;
            top: 267px;
            border: lightgray solid 1px;
            width: 92%;
            height: 50px;
            text-align: center;
            line-height: 50px;
            font-size: 20px;
            color: #3fac24;
            text-decoration: none;
        }
        #moreinfo:hover{
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div id="topElem">
        <div id="top">Mobile Phone Number Ownership Professional Query</div>
        <div id="haomaduan">Phone number(paragraph):</div>
            <input value="" id="srch" type="text" placeholder="Please enter the phone number you need to query"/>
            <button type="button" class="btn">query</button>
    </div>
    <div id="bodypart" style="visibility: hidden">
        <div id="chaxjg">Query Results</div>
        <div id="number">The segment of mobile phone number you query</div>
        <div id="number_json"></div>
        <div id="cityinfo">Card Number Ownership</div>
        <div id="cityinfo_json"></div>
        <div id="companyinfo">Subordinate to Communications Company</div>
        <div id="companyinfo_json"></div>
        <div id="cityblock">Area code</div>
        <div id="cityblock_json"></div>
        <div id="postcode">Zip Code</div>
        <div id="postcode_json"></div>
        <a id="moreinfo" href="https://Cn.bing.com/search?Q=%E4%B8%AD%E5%9B%BD%E5%90%90%84%E5%9B%BD%E5%90%84%E5%9C%B0%E9%82%82%AE%E7%E7%BC%96%E5%8C%BA%E5%8F%8F%B7&cvid=a2ac39fe100d44c09adb028181434de5&aqs=edge..69i57j0.9831j0 j1&pglt=41&FORM=NTA1&PC=DCTS">DCTS&DCTS&DCTS&DCTS>>>More details postal area code number <<>DCDCTS>DCTS>DC/a>
    </div>
</body>
<script type="text/javascript">
    //Bind click event, click button to search
    $('button').click(function() {
        //Show hidden query result boxes
        var inv = document.getElementById("bodypart");
        var attr = document.createAttribute("style");
        attr.value = "visibility:visible";
        inv.setAttributeNode(attr);
        //Send AJAX
        var mobile=document.getElementById("srch").value;
        var city;
        var company;
        var block;
        var postcode;
        $.ajax({
            type: "GET",
            url : "https://tool.bitefu.net/shouji/?mobile="+mobile,
            jsonp: "callback",
            success: function(respData) { //The JSON string of the background response, which automatically converts you to a JSON object
                console.log(respData);
                mobile = respData.mobile;
                city = respData.province+" "+respData.city;
                company = respData.isp;
                block = respData.areacode;
                postcode = respData.postcode;

                var text1 = document.getElementById("number_json");
                text1.innerText = mobile;

                var text2 = document.getElementById("cityinfo_json");
                text2.innerText = city;

                var text3 = document.getElementById("companyinfo_json");
                text3.innerText = company;

                var text4 = document.getElementById("cityblock_json");
                text4.innerText = block;

                var text5 = document.getElementById("postcode_json");
                text5.innerText = postcode;

                if(respData.info){
                    alert(respData.info);
                    text1.innerText = '';
                    text2.innerText = '';
                    text3.innerText = '';
                    text4.innerText = '';
                    text5.innerText = '';
                }
            },
            dataType:"jsonp"
        });
    });
</script>
</html>

Effect:
Interface when not queried:

Query normal interface:

Interfaces and pop-up reminders when query input is illegal:

Click on the page after confirming in the pop-up window:

Page jump after clicking more details:

Posted by jdsflash on Fri, 03 Sep 2021 09:16:22 -0700