Introduction to jQuery, including load (), get (), post (), assignment and other methods (case analysis)

Time:2021-6-11

1. What is jQuery

JQuery is a framework collection of JavaScript, not a new technology.

2. What’s the use of jQuery

-Write less and do more
-Free, open source and lightweight JS library, small capacity
 Note: in the project, it is recommended to refer to the JS Library of Min version
-Compatible with mainstream browsers in the market, such as ie, Firefox and chrome
        Note: jQuery does not encapsulate all JS, it just encapsulates selectively
-It can process HTML / JSP / XML, CSS, DOM, events, achieve animation effect, and also provide asynchronous Ajax function
-The documentation manual is complete and detailed
-Mature plug-ins are available
-It is advocated to provide an ID attribute for the main HTML tags, but it is not necessary
-After the error, there is a certain prompt message
-There is no need to insert a lot of JS in HTML to call commands
Copy code

3. Ajax and jquery

Introduction to jQuery, including load (), get (), post (), assignment and other methods (case analysis)

1. JS is a front-end language. 2. AJAX is a technology, which provides an asynchronous update mechanism, using the exchange of data between the client and server rather than the entire page document, to achieve partial page update. 3. JQuery is a framework that encapsulates JS to make it easier to use. JQuery makes the use of JS and Ajax more convenient

4. Use:

1. Reference jquery.js file

<script type="text/javascript"></script>
Copy code

2. Common methods.load()

$(“#div01”).load(“userservlet”); Explanation: find the tag with page ID div01, and then load the file with the path of userservlet, here the servlet path.

$(“#div01”)Equivalent to document. Getelementbyid (“div01”) in JavaScript

$.get(url,function(data){});

A get request is used to transfer data to the server without adding function () and returning without parameters. If you need to add the requested parameters, you can directly add them to the URL, such as “usernameservlet? Name =” Eric “; If you need a return value, add a data callback function.

$.post(url,data,callback);

Submitted data to the server in post mode and returned URL: the path of the control class to be processed data: the data passed like the server in the format of {Name: “Zhangsan”, age = “18”} callback: get the callback function returned by the server in the format of function (data, status) {}, status means status and 200 means success.

eg:

$.post("<%=basePath%>customer/update.action",$("#edit_customer_form").serialize(),function(data){  
      if(data=="1"){
      Alert ("customer information updated successfully!");
      }else{
        Alert ("customer information update failed!");
      }
      window.location.reload();
    });
Function 2:
If (confirm ('are you sure you want to delete this customer?){
    $.post("<%=basePath%>customer/delete.action",{"id":id},function(data){
    if(data=="1"){
    Alert ("customer deleted successfully!");
    }else{
    Alert ("customer information deletion failed!");
    }
    window.location.reload();
    });
        }
Copy code

Note: there are two points mentioned above$(“form”).serialize()

Jquery ajax() uses serialize() to submit form data. If you print the value of $(“form”). Serialize(), the format is: id = 12 & name = “Eric” & age = 18 & city = “AA”…., then the problem is, how should we receive it in the controller of the server? Receive with @ ResponseBodyconfirm(”)

There are three kinds of pop-up boxes (alert, confirm, prompt) in JavaScript

  • 1. Alert is a warning message box.
  • 2. Confirm (“the information you want the user to confirm”) confirmation message box. First, the return value of the confirm method is true or false
  • 3. Prompt() prompt message box the user can input an answer in the section to respond to your prompt and return a user’s input value

.val(),.html(),.text()

JQuery gets the tag value and assignment method. The following is the difference between the three methods:

  • $(“#div01”).val()

    • Val(), which means to get the value value in div01 tag;
    • Val (“AAA”) assigns a value to an element with a value attribute. In fact, it assigns AAA to the value of the element
  • $(“#div01”).html()

    • . html() gets the value in the body of the tag with ID div01
    • . HTML (“” option value = ‘> “) for a certain element, you can use the element that contains a section of value on the left and right. For example,. HTML (“font / font”)
  • $(“#dov01”).text()

    • . text () is the same as HTML, just a code that supports HTML
    • . text (“aaaaaa”) this method works for assignments that can write values in two tags. For example: div / div

$.ajax()

Layer implementation based on the use of Ajax, the key is how to write the internal parameters, here directly on the code

function editCustomer(id) {
$.ajax({
    type:"get",
    url:"<%=basePath%>customer/edit.action",
    data:{"id":id},
    success:function(data) {
    $("#edit_cust_id").val(data.cust_id);
    $("#edit_customerName").val(data.cust_name);
    $("#edit_customerFrom").val(data.cust_source)
    $("#edit_custIndustry").val(data.cust_industry)
    $("#edit_custLevel").val(data.cust_level)
    $("#edit_linkMan").val(data.cust_linkman);
    $("#edit_phone").val(data.cust_phone);
    $("#edit_mobile").val(data.cust_mobile);
    $("#edit_zipcode").val(data.cust_zipcode);
    $("#edit_address").val(data.cust_address);
      }
   });
}
Copy code

There is one point above, that is, the returned data. Data is returned directly by the controller layer using @ ResponseBody in the form of JSON.

Case 1. Imitating Baidu tips

Demand: when we use Baidu, it will give us a prompt after entering a few characters, so how does the front-end page realize the response?

Thinking:: use. Keyup to get the event of the keyboard popping up, and then get the value of the input box. That is, every time the keyboard pops up, the value of the input box will be obtained. After getting the value of the input box, the data will be sent (post) to the controller layer. The controller calls service layer > persistence layer > to get the information of the database, and then returns it to the front page.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript"></script>
<script type="text/javascript"src="../js/baidu.js"></script>
<title>Insert title here</title>
</head>
<body background="../105.jpg">
<center>
    <h2>Baidu</h2>
    <input type="text" id="word" style="width:500px;height:50px"/>
    < input type = "button" value = "search" style=“ width:80px; height:56px "/>
    <div id="div01" style="position:relative;left:-43px; width:500px;height:300px;border: 1px solid blue;display: none"></div>
</center>
</body>
</html>
Copy code

js:

//The entry function used to be $(document). Ready (fuction () {})
//Gets the event that the keyboard pops up
$(function(){
    $("#word").keyup(function() {
        //Get the information in the input box and upload it
    //    alert("asd");
        var word=$(this).val();
        //alert(word);
        $.post("/AjaxAndJQuery/findServlet",{words:word},function(data,status){
            //alert(data);
            //The returned data is a JSP page. Now we put it in the specified Div
            if(word==""){
                $("#div01").hide();
            }else{
            $("#div01").show();
            $("#div01").html(data);
            }
        });
    })
});
Copy code

Controller (servlet is used here)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
    //Get data, query database, return data value
    request.setCharacterEncoding("utf-8");
    String word = request.getParameter("words");
    //
    findDao findDaoImpl = new findDaoImpl();
    List<String> list = findDaoImpl.findInformation(word);
    //Print the content obtained from the database
    for (String news : list) {
    System.out.println(news);
    }
    request.setAttribute("words", list);
    response.setContentType("text/html;charset=utf-8");
    /**
     *It returns the page to the person who requests it. Generally, we use the browser to access it, and it returns the page to the browser
     *When I use jQuery to access, it returns the data to jQuery and puts it in the data
     */
    request.getRequestDispatcher("/JQueryFind/list.jsp").forward(request, response);
    } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
Copy code

Note: a JSP page is returned here, that is to say, the data in jQuery is a JSP page list. JSP

<body>
    <table style="width:500px">
        <c:forEach items="${words}" var="word">
            <tr>
                <td>${word}</td>
            </tr>
        </c:forEach>
    </table>
</body>
Copy code

Case 2: provincial and municipal linkage

Demand: when we register, we may choose a city. For example, when you select Hubei for Province, the corresponding city will automatically refresh to the city below Hubei. How is the logic of the front page realized?

Thinking:First, the label of the province element is found. Then, according to the. Change event, when it changes, its value is sent to the controller layer through $. Post(), and the control layer returns the result (expressed asXMLorJson)It’s the same way.

Here is the first: the controller layer communicates with the front-end page through XML

Controller (servlet implementation)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1. Get parameters
            int pic = Integer.parseInt(request.getParameter("pic"));
            //2. Get city list
            cityDao cityImpl = new cityDaoImpl();

            List<city> findCity = cityImpl.findCity(pic);
            //3. Return it
            //Returned as XML
            XStream xstream=new XStream();
            //Set class alias
            xstream.alias("city", city.class);
            //Use class members as properties
            xstream.useAttributeFor(city.class, "pic");
            String xml = xstream.toXML(findCity);

            //Set return format
            response.setContentType("text/xml;charset=utf-8");
            response.getWriter().write(xml);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Copy code

Note: xStream xStream = new xstream(); Convert an object to the form of XML or XML to the format of an object. I found a more detailed blog:

www.cnblogs.com/mengfanrong…

JS:

$(function(){
    //1. Find the element of the province, and request the element of the province once it changes
    $("#province").change(function(){
        //Get the value of province
        var pic=$(this).val();
        //Post request
        $.post("/AjaxAndJQuery/findCity",{pic:pic},function(data,status){
            //There is a data callback status for the returned status value, 200 for OK
            //What is returned is an XML document, and what is needed is the value in the < name > tag
            /*
             *  <city pic="2">
                 < name > Huizhou < / name >
                </city>
                 <city pic="2">
                 < name > Meizhou
                </city>
             */
            //Clear previously queried values
            $("#city"). HTML ("< option value = '> - please select -");
            $(data).find("city").each(function(){    
                //It means that every element traversed goes through this method. Once traversing City, fuction method is executed
                //. find ("city") to get all the cities, and then traverse
                //var pic=$(this).children("")
                var name=$(this).children("name").text();
                //alert(name);
                //It can be found in the add column of the manual
                $("#city").append("<option value=''>"+name);
            });
        });
    });
})
Copy code

jsp:

<body>
    province:
    <select name="province" id="province">
        < option value = > - please select-
        < option value = "1" > Hubei
        < option value = "2" > Guangdong
        < option value = "3" > Shandong
        < option value = "4" > Henan
    </select>
    city:
    <select name="city" id="city">
        < option value = > - please select-
    </select>
</body>
Copy code

Method 2: cotoller interacts with the front page through JSON. Description: you can directly use the following methods (@ ResponseBody)

@RequestMapping("edit")
    @ResponseBody
    /**
     *JSP page directly receives a JSON string, so the object is directly converted into JSON data format
     * @param id
     * @return
     */
    public Customer edit(Integer id){
        Customer customer = customerService.getCustomerById(id);
        return customer;
    }
Copy code

However, because my case is written by using servlet, that is, you need to assemble the JSON string (you can assemble it manually or through the tool class), here we use jsonarray. Jsonarray = jsonarray. Fromobject (FindCity);

servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1. Get parameters
            int pic = Integer.parseInt(request.getParameter("pic"));
            //2. Get city list
            cityDao cityImpl = new cityDaoImpl();

            List<city> findCity = cityImpl.findCity(pic);
            //3. Return it
            //Returned in the form of JSON
            JSONArray jsonArray = JSONArray.fromObject(findCity);
            String json = jsonArray.toString();

            System.out.println(json);
            //Set return format
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write(json);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
Copy code

js:

$(function(){
    //1. Find the element of the province, and request the element of the province once it changes
    $("#province").change(function(){
    //Get the value of province
    var pic=$(this).val();
    //Post request
    $.post("/AjaxAndJQuery/findCityJson",{pic:pic},function(data,status){
    //There is a data callback status for the returned status value, 200 for OK
    /**
     *The returned data is a string in the form of JSON
     *[{"name": "Guangzhou", "pic": 2}, {"name": "Shenzhen", "pic": 2}, {"name": "Huizhou", "pic": 2}, {"name": "Meizhou", "pic": 2}]
     */
    //Clear previously queried values
    $("#city"). HTML ("< option value = '> - please select -");
    //Traverse the data to get the {} content in 〔 and access its value through the city. Attribute. City customization is equivalent to encapsulating {} as an object
    $(data).each(function(index,city){
    $("#city").append("<option value=''>"+city.name);
      });
    },"json");
    });
})
Copy code

Jsp: same as above