Jquery is that simple

What is Jquery?

Jquey is a JavaScript library across mainstream browsers that simplifies JavaScript's manipulation of HTML

It is a JavaScript library that encapsulates JavaScript and simplifies our writing code

Why use Jquery?

I think the very important reason is that it is compatible with the mainstream browsers on the market. We know it by learning AJAX. IE and FireFox have different ways of obtaining asynchronous objects, and Jquery can block these incompatible things .. .

  • (1) Write less code and do more things [write less do more]
  • (2) Free, open source and lightweight js library with small capacity
  • Note: In the project, it is recommended to refer to the min version of the js library
  • (3) Compatible with mainstream browsers on the market, such as IE, Firefox, Chrome
  • Note: jQuery does not encapsulate all JS, but only selectively encapsulates it
  • (4) Can handle HTML/JSP/XML, CSS, DOM, events, achieve animation effects, and also provide asynchronous AJAX functions
  • (5) The documentation manual is very complete and detailed
  • (6) Mature plug-ins to choose from
  • (7) It is advisable to provide an id attribute to the main html tag, but it is not required
  • (8) After an error occurs, there is a certain prompt message
  • (9) No need to insert a lot of js through tags in html <script>to call commands

review javascript

There are three basic ways that JavaScript locates controls in HTML:

  • (A) Via the ID property: document.getElementById()
  • (B) Via the NAME property: document.getElementsByName()
  • (C) By tag name: document.getElementsByTagName()

We found that JavaScript method names are too long to write code easily ...

Package optimization

These method names are too long, and there are no three methods to get the controls of ID attribute, NAME attribute, and tag name attribute. We just define the rules.

  • The incoming parameter is a string starting with "#", then it is the id attribute
  • The incoming parameter is a string that does not start with "#", and the string without prefix modification is the tag name attribute

At this point, we can judge whether it is the control that gets the ID property or the control that gets the label name according to the incoming parameters . Internally, these methods are still called document.getElementById(). When we actually use it, we can directly write the string of our custom rule to get the corresponding control.


	<script type="text/javascript">
		//$()表示定位指定的标签
		function $(str){
			//获取str变量的类型
			var type = typeof(str);
			//如果是string类型的话
			if(type == "string"){
				//截取字符串的第一个字符
				var first = str.substring(0,1);
				//如果是#号的话
				if("#" == first){
					//获取#号之后的所有字符串
					var end = str.substring(1,str.length);
					//根据id定位标签
					var element = document.getElementById(end);
					//如果找到了
					if(element != null){
						//返回标签
						return element;
					}else{
						alert("查无此标签");
					}
				}else{
				
				}
			}else{
				alert("参数必须是字符串类型");
			}
		}
	</script>

The relationship between JQuery objects and JavaScript objects

  • Objects created with JavaScript syntax are called JavaScript objects
  • Objects created with JQurey syntax are called JQuery objects
    • The Jquery object can only call the API of the Jquery object
    • JavaScript objects can only call APIs of JavaScript objects

 

write picture description here

 

JQuery objects and JavaScript objects can be converted into each other . Generally, because Jquery is more convenient to use, we convert JavaScript objects into Jquery objects.

Convert Jquery to JavaScript object

Objects are treated as arrays in Jquery. Therefore, the syntax for converting Jquery into a JavaScript object is as follows: Get the subscript of the array, and the result is a JavaScript object.

  • jQuery object [subscript, 0-based]
  • jQuery object.get (subscript, starting from 0)

To reiterate: Jquery objects can only call APIs of Jquery objects, and JavaScript objects can only call APIs of JavaScript objects

Convert JavaScript object to Jquery

It is worth noting that in JavaScript scripts, this represents the JavaScript object .

The syntax for converting a JavaScript object into a Jquery object is also very simple: write a JavaScript object in ${}, and it becomes a JQuery object.

  • Syntax: $(js object)---->jQuery object

Generally, we are accustomed to write $ in front of the variables of the Jquery object, indicating that this is a JQuery object \

Selector

Jquery provides nine selectors for us to use to locate HTML controls..

  • Purpose: Through nine types of selectors, you can locate any tags in web pages (HTML/JSP/XML)
    • (1) Basic selector
      • Directly locate id, class modifier, label
    • (2) Hierarchical selector
      • Labels with father and son, brotherhood
    • (3) Enhance the basic selector
      • Labels for greater than, less than, equal to, odd and even numbers
    • (4) Content selector
      • Define the content as XXX, whether there is a tagger in the content, a tag with child elements or text
    • (5) Visibility selector
      • Visible or invisible labels
    • (6) Attribute selector
      • related to the value of the property
    • (7) Child element selector
      • matches child tags under parent tags
    • (8) Form selector
      • Match the control properties corresponding to the form
    • (9) Form object attribute selector
      • Match the specific value of the form attribute

With these nine selectors, we can basically get tags anywhere in HTML.

 

write picture description here

 

Jquery API on DOM

I used Jquery's selector earlier to get the HTML tags, and it is useless to simply get the tags. We need to add, delete, and modify it, so that we can make a "dynamic" effect on the web page ...

The DOM of JavaScript can manipulate CSS and HTML to make dynamic effects on web pages.

 

write picture description here

 

**Jquery is an encapsulation of JavaScript, so after getting the HTML tag, Jquery also has a corresponding method to obtain the content of the tag, and dynamically create, delete, and modify the tag. **Thereby making a dynamic effect on the web page

addition

  • append(): Append to the parent element
  • prepend(): Append before parent element
  • after(): Append after sibling elements
  • before(): Append before sibling elements

query hierarchy

We found that there are hierarchical selectors on the selector, and there are also hierarchical methods on the API. Generally, we use methods to locate the corresponding controls .

  • children(): query only child nodes, excluding descendant nodes
  • next(): the next sibling node
  • prev(): go to the next sibling node
  • siblings(): upper and lower sibling nodes

css style

  • addClass(): add an existing style
  • removeClass(): remove an existing style
  • hasClass(): Determines whether the label has the specified style, true means there is a style, false means no style
  • toggleClass(): If the label has a style, delete it, otherwise add the style

animation effect

Set parameters under these methods, then you can control its hiding and display time

  • show(): show the object
  • hide(): hide the object
  • fadeIn(): fade in the display object
  • fadeOut(): fade out hidden objects
  • slideUp(): slide up
  • slideDown(): slide down
  • slideToggle(): switch sliding up and down, faster

CSS size property

Calling directly without parameters is to obtain, and to specify parameters is to modify

  • offset(): Get the left and top coordinates of the object
  • offset({top:100,left:200}): Position the object directly to the specified left and top coordinates
  • width(): Get the width of the object
    • width(300): Set the width of the object
  • height(): Get the height of the object
    • height(500): Set the height of the object

Label content and attributes

  • val(): Get the value of the value attribute
    • val(""): Set the value attribute value to "" empty string, which is equivalent to emptying
  • text(): Get the value between HTML or XML tags
    • text(""): Set the value between HTML or XML tags to "" empty string
  • html(): Get the value of HTML under the tag
  • **attr(name,value): Add key-value attribute pair to eligible tags**
  • removeAttr(): removes an existing attribute

Add, delete and modify tags

  • ** $("<div id='xxID'>HTML代码</div>"): create element, attribute, text **
  • remove(): deletes itself and its descendants
  • clone(): copy only styles, not behavior
  • clone(true): Copy both style and behavior
  • replaceWith(): replace the original node

iterate

Since the Jquery object is regarded as an array, the each() method is specially used to manipulate the array .

  • each(): is a method in jQuery dedicated to iterating arrays, the parameter is a processing function, this represents the js object that needs to be iterated currently

Jquery event API

A major feature of JavaScript is event-driven. When the user performs certain actions, JavaScript will respond to the event. In the event method, we can "feed back" some information to the user for the user's action!

Jquery also encapsulates JavaScript events . Let's take a look at the following API:

  • window.onload: Triggered when the browser loads the web page, you can write multiple onload events, but the latter overrides the former
  • ready: Triggered when the browser loads the web page, you can write multiple ready events, the latter will not overwrite the former, and execute from top to bottom in turn, we often use $(function) to simplify
    • When ready and onload exist at the same time, both will trigger execution, and ready is faster than onload
  • change: Triggered when the content changes
  • focus: focus acquisition
  • select: select all text values
  • keyup/keydown/keypress: Demonstrate the difference between getting event objects in IE and Firefox
  • mousemove: Triggered by continuously moving in the specified area
  • mouseover: fires when the mouse moves in
  • mouseout: fires when the mouse is moved out
  • submit: Triggered when the form is submitted, true means submitted to the background, false means not submitted to the background
  • click: click trigger
  • dblclick: double-click trigger
  • blur: focus lost

It is worth noting that when the user performs an action, the browser will automatically create an event object and pass it to the method that responds to the event [similar to the principle of a listener] , then we can get some properties on the response method:

 

write picture description here

 

Jquery commonly used API for ajax

When we started to use JavaScript to learn AJAX, when creating asynchronous objects, we needed to create different objects according to different browsers.... When loading XML files, there were also compatibility issues.

Jquery is very good at shielding different browser problems, and there is no need to consider browser compatibility issues , which is very, very convenient for us to develop.

  • **$.ajax([options]) **
  • load(url, [data], [callback])
  • **$.get(url, [data], [fn], [type]) **
  • $post(url, [data], [callback], [type])
  • serialize()

The functions of the first four methods are similar, they all send requests to the server and get the data returned by the server .

The last one is to encapsulate the data of the form and encapsulate the data of the form into JSON format

load()

First, let's use the load() method. This is how it is explained in the documentation.

 

write picture description here

 

Let me add:

  • The first parameter: indicates the path to be requested
  • The second parameter: which parameters should be brought to the server side, it needs to be in JSON format
  • The third parameter: the callback method, which will be called when the server returns to the asynchronous object

The callback method also has three parameters:

  • Parameter 1 in the callback function: backData represents the returned data, which is a js object
  • The second parameter in the callback function: textStatus indicates the textual description of the return status, for example: success, error,
  • Parameter three in the callback function: xmlHttpRequest represents the core object in ajax

In general, we only need to use the first parameter!

Let's use this method to get the current time , familiarize yourself with this method:

The jquery object that calls the load method, the returned result is automatically added to the middle of the label represented by the jQuery object

  • If there are parameters, post is automatically used, and get is automatically used without parameters.
  • When using the load method, coding is performed automatically, no manual coding is required

<%--
  Created by IntelliJ IDEA.
  User: ozc
  Date: 2017/5/18
  Time: 13:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
  <head>
    <title>$Title$</title>

    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>

  </head>
  <body>
  当前时间是:<span id="time"></span><br>
  <input type="button" id="button" value="获取当前时间">

  <script type="text/javascript">

    $("#button").click(function () {


      //请求服务器端的路径
      var url = "${pageContext.request.contextPath}/TimeServlet?time?" + new Date().getTime();

      //没有要参数要带过去
      //var sendData = null;

      /*
	   * function方法的三个参数:	
	       * 第一个参数表示服务器端带回来的数据,是JS对象
	       * 第二个参数表示的是返回状态的文字描述【用处不大】
	       * 第三个参数表示的是异步对象,一般我们用来看服务器端返回的JSON的值是什么【用处还行】
	       *       因为第一个参数返回的是JS对象,因此我们是看不见具体JSON的值是什么,所以有的时候要用第三个参数
       *
       * 值得注意的是:
       *       要想使用第三个参数,就必须把前两个参数给写上!
       *       调用load方法的jquery对象,返回结果自动添加到jQuery对象代表的标签中间
       * */
      $("#time").load(url);

    });

  </script>


  </body>
</html>

  • Servlet code:


    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String date = dateFormat.format(new Date());

        PrintWriter writer = response.getWriter();
        writer.write(date);

        writer.flush();
        writer.close();

    }

  • Effect:

 

write picture description here

 

$.get()

The above load() method, when we bring parameters to the server, is automatically converted to post, and when there is no parameter, it is converted to get. $.get() is to specify the get method

The load() method is called using the Jquery object, and after the call, the data will be automatically filled into the label of the Jquery object, and $.get() is not called by a specific Jquery object!

The parameters of $.get(url, [data], [fn], [type]) are completely similar to load(), we should just do it in the above example.

Since $.get() does not automatically fill the returned data into the label, it needs to be added to the specified label manually!


      $.get(url, function (backData) {

        //得到客户端返回的数据【JS对象】

        $("#time").append(backData);
      });

  • Effect:

 

write picture description here

 

$.post()

.post() and.get() is very similar, but the request method is changed. In general, when we have parameters to pass to the server, we use the post method.

Using the $.post() method requires setting the encoding, which is different from the load() method!

The two methods are illustrated below using the case of checking whether the username and password are valid :


<%--
  Created by IntelliJ IDEA.
  User: ozc
  Date: 2017/5/18
  Time: 13:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>$Title$</title>

    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>

</head>
<body>

<%--使用异步操作,表单的form和method都不是必须的,如果指定了,还是会根据后面Jquery的方法和参数来决定--%>
<form>

    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text"></td>
        </tr>

        <tr>
            <td>密码:</td>
            <td><input type="password"></td>
        </tr>

        <tr>
            <td><input type="button" value="检查"></td>
        </tr>
    </table>
    <span id="backData"></span>
</form>

<script type="text/javascript">

    $(":button").click(function () {

        var url = "${pageContext.request.contextPath}/UserServlet?time=" + new Date().getTime();

        //要传送过去的数据必须是JSON格式的
        var sendData = {
            username: $(":text").val(),
            password: $(":password").val()
        };

        $.post(url, sendData, function (backData) {

            //得到返回的数据,填充到相对应的位置
            $("#backData").text(backData);

        });


    });


</script>


</body>
</html>

  • Servlet code:

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by ozc on 2017/5/21.
 */
@WebServlet(name = "UserServlet",urlPatterns = "/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //设定编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String backData = "用户名和密码合法";
        if ("哈哈".equals(username) && "123".equals(password)) {

            backData = "用户名或密码不合法";
        }

        response.getWriter().write(backData);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doPost(request, response);

    }
}

 

write picture description here

write picture description here

 

serialize()

As I mentioned above when I introduced the parameters, the parameters sent to the server need to be in JSON format, but what if I have a lot of parameters in the form? ? ? Isn't that asking me to splicing them one by one ? ? ? ?

Therefore, Jquery also provides a method of serialize(), which automatically encapsulates the data in the form into JSON format data for us.

Before using it, pay attention to:

  • Set a name attribute for each jQuery object, because the name attribute will be considered the request parameter name
  • must be inside a <form>tag element

According to the above example, let's use it, we call the serialize() method without splicing JSON ourselves


<%--
  Created by IntelliJ IDEA.
  User: ozc
  Date: 2017/5/18
  Time: 13:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>$Title$</title>

    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>

</head>
<body>

<%--使用异步操作,表单的form和method都不是必须的,如果指定了,还是会根据后面Jquery的方法和参数来决定--%>
<form>
    <table>


        <%--要想使用serialize这个方法,就必须在表单之内,并且给上对应的name属性--%>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>

        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>

        <tr>
            <td><input type="button" value="检查"></td>
        </tr>
    </table>
    <span id="backData"></span>
</form>

<script type="text/javascript">

    $(":button").click(function () {

        var url = "${pageContext.request.contextPath}/UserServlet?time=" + new Date().getTime();

        //要传送过去的数据必须是JSON格式的
/*        var sendData = {
            username: $(":text").val(),
            password: $(":password").val()
        };*/

        var sendData = $("form").serialize();
        $.post(url, sendData, function (backData) {

            //得到返回的数据,填充到相对应的位置
            $("#backData").text(backData);

        });
        
    });


</script>


</body>
</html>

  • Effect:

 

write picture description here

 

$.ajax()

For this method, let's use the case of secondary linkage to explain it. We have used JavaScript to parse XML and JSON to achieve secondary linkage. This time I use Jquery+Struts2+JSON to achieve secondary linkage.

The parameter received by the $.ajax() method is a JSON type , and there are several parameters in JSON:

  • type [request type]
  • url [request path]
  • data [data sent to the server, also a JSON type]
  • success [callback function]

The problem encountered here: When dynamically obtaining the value of the selection drop-down box, val() is called instead of text()....


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>省份-城市,基于jQuery的AJAX二级联动</title>
    <script type="text/javascript" src="js/jquery-1.8.2.js"></script>
</head>
<body>

<%--############前台页面##############################--%>
<select name="province" id="provinceId">
    <option>请选择省份</option>
    <option>广东</option>
    <option>北京</option>
</select>
<select name="city" id="cityId">
    <option>请选择城市</option>
</select>


<%--############监听省份##############################--%>
<script type="text/javascript">
    $("#provinceId").change( function() {

        //每次调用的时候,把城市的值清空,除了第一项
        $("#cityId option:gt(0)").remove();


        //得到具体选择的值,讲道理这里应该是test的,可是test()没反应,要用val()
        var province = $("#provinceId option:selected").val();

        //如果不是“请选择省份”,才触发事件
        if ("请选择省份" != province) {

            //它接收的是一个JSON类型的数据
            $.ajax(
                    {
                        type: "POST",
                        url: "${pageContext.request.contextPath}/findCityByProvince?time=" + new Date().getTime(),
                        data: {"province": province},
                        success: function (backData, aaa, ajax) {

                            //看下服务器带过来的数据是什么样的,然后再对JSON进行解析
                            //alert(ajax.responseText);

                            //得到服务器返回的数据,是一个JSON格式数据
                            var array = backData.city;
                            for(var i=0;i<array.length;i++) {

                                //动态创建option节点,添加到城市下拉框中
                                var $option  = $("<option>" + array[i] + "</option>");
                                $("#cityId").append($option);
                            }
                        }
                    }
            );
        }
    });
    
</script>

  • Action

import com.opensymphony.xwork2.ActionSupport;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ozc on 2017/5/18.
 */
public class ProvinceAction  extends ActionSupport{

    //自动封装数据
    private String province;

    public String getProvince() {
        return province;
    }
    public void setProvince(String province) {
        this.province = province;
    }
    
    //封装城市的集合
    private List<String> city = new ArrayList<>();
    public List<String> getCity() {
        return city;
    }


    public String findCityByProvince() throws Exception {

        if ("广东".equals(province)) {
            city.add("广州");
            city.add("珠海");
            city.add("从化");
        } else if ("北京".equals(province)) {
            city.add("一环");
            city.add("二环");
            city.add("三环");
            city.add("四环");

        } else {
            System.out.println("没有你选择的地区");

        }
        return "ok";
    }

}

  • Struts.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">


<struts>
   <package name="province" extends="json-default" namespace="/">

        <global-results>
            <result name="ok" type="json"></result>
        </global-results>
        <action name="findCityByProvince" class="ProvinceAction" method="findCityByProvince">
        </action>

    </package>
</struts>
  • Effect:

 

write picture description here

 

Summarize

  • The load() method is called using the Jquery object, and the result obtained from the server will automatically nest the result into the tag where it is located.
  • The get() method is not called using the Jquery object, so you need to manually place the result where you want it
  • The post() method is used to bring parameters to the server, so we need to manually set the encoding on the servlet. The usage is the same as the get() method
  • serialize() is a very useful method. It does not require us to manually splice the parameters, and will automatically encapsulate the parameters of the form form into JSON format data.
  • As for the $.ajax() method, it is actually a collection of get() and post() methods.

 

 

 

 

 

 

If there are any mistakes in the article, please correct me, and we can communicate with each other. Students who are accustomed to reading technical articles on WeChat and want to get more Java resources can follow WeChat public account: Java3y

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325142218&siteId=291194637