1. What is JQuery

JQuery is a collection of frameworks for javascript, not a new technology.

2. What is Jquery for

- Write less, do moredoMore 】 - free, open source and lightweight JS library, small capacity note: in the project, advocate reference to the min version of js library - compatible with mainstream browsers on the market, such as IE, Firefox, Chrome note: JQuery does not encapsulate all JS, but only selectively - it can handle HTML/JSP/XML, CSS, DOM, events, animations, and asynchronous AJAX functionality - the documentation is complete, Very detailed - mature plugins are available - it is recommended to provide an ID attribute for the main HTML tag, but not required - there are certain messages when errors occur - no need to insert a lot of JS into the HTML to invoke commands through <script> tagsCopy the code

3. Ajax and JQuery

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

4. Use:

1. Reference the jquery. js file

<script type="text/javascript" src="Js/jquery - 1.11.3. Min. Js." "></script>
Copy the code

2. Load ()

$(“#div01”).load(“userservlet”); Find the TAB with page ID div01 and load the file with path userservlet.

$(“#div01”) equivalent to document.getelementById (“div01”) in JavaScript

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

A get request is used to send data to the server without function(). If you need to add a request parameter, add it to the URL. For example, “usernameServlet? name=”eric”; If a return value is required, add a data callback function

$.post(url,data,callback);

The data has been submitted to the server in post mode and the url is returned: the path of the control class being processed. Data: The data passed by the server is in the following format: {name:”zhangsan”,age=”18″} callback: obtains the callback function returned by the server in the format of function(data,status){}, where status indicates the status and 200 indicates 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("Failed to delete customer information!");
	}
	window.location.reload();
	});
		}
Copy the code

$(“form”).serialize()

JQuery Ajax () uses serialize() to submit form data. If $(“form”).serialize() is printed, the format is id=12&name=” Eric “&age=18&city=”aa”……. So, the question is, how do we receive it in the Controller of the server? Accept confirm(“) with @responseBody

There are three types of pop-up boxes in JavaScript (Alert, confirm, prompt)

  • 1. Alert message box
  • First: The confirm method returns true or false
  • The user can respond to your prompt by typing an answer in the section that returns a user’s input value

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

Select * from tag; select * from tag;

  • $(“#div01”).val()
    • Val (), to obtain the value of the tag whose ID is div01;
    • Val (“aaa”) assigns a value to the element with the value attribute, essentially assigning the element’s value aaa
  • $(“#div01”).html()
    • .html() gets the value in the body of the tag with id div01
    • .html(“” option Value = “” >””) For an element, you can assign the value to the element that contains a value around the element. For example:.html(” font “/font “)
  • $(“#dov01”).text()
    • .text() works the same as HTML, just a supporting HTML code
    • .text(” aaaaaa “) This method works for assignments that can write values in both labels. For example: div aaaaaaaa /div

$.ajax()

The implementation of the layer is based on the use of Ajax, the key is how to write 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 the code

So there’s one point, and that’s the data that’s being returned, and the data is being returned directly as Json by the Controller layer using @responseBody.

Case 1. Imitation of Baidu prompt

Requirements: in our use of Baidu, often in the input of a few characters, it will give us a prompt, so how to achieve the front-end page response?

: : Use. Keyup to get the event that the keyboard is up, and then get the value of the input box, that is, every time the keyboard is up, get the value of the input box, then send the data (Post) to the Controller layer, the Controller calls the service layer -> persistence layer -> get the database information, Return it to the front page.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src=".. / js/jquery - 1.11.3. Min. Js. ""></script>
<script type="text/javascript"src=".. /js/baidu.js"></script>
<title>Insert title here</title>
</head>
<body background=".. /105.jpg"> <center> <h2> </h2> <inputtype="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 the code

js:

$(document).ready(fuction(){}) // Get the event $(function(){
	$("#word").keyup(function() {// get the information from the input box, and then upload // alert("asd");
		var word=$(this).val();
		//alert(word);
		$.post("/AjaxAndJQuery/findServlet",{words:word},function(data,status){ //alert(data); // The data returned is a JSP page, which we now place in the specified divif(word==""){
				$("#div01").hide();
			}else{$("#div01").show();
			$("#div01").html(data); }}); })});Copy the code

Controller(servlet used here) :

protected void doGet(HttpServletRequest Request, HttpServletResponse Response) throws ServletException, IOException {try {// Obtain data, query database, Return the data value request. SetCharacterEncoding ("utf-8");
	String word = request.getParameter("words"); // findDao findDaoImpl = new findDaoImpl(); List<String> list = findDaoImpl.findInformation(word); // Prints the contents obtained from the databasefor (String news : list) {
	System.out.println(news);
	}
	request.setAttribute("words", list);
	response.setContentType("text/html; charset=utf-8"); / * * * who request, it is returned to the page who, generally we are using a browser to access, it will return to the page to the browser * when I use JQuery to visit, it is the data returned to the JQuery, inside the data data * / request. GetRequestDispatcher ("/JQueryFind/list.jsp").forward(request, response); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code

Note: What is returned here is a JSP page, that is, 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 the code

Case 2. Linkage between provinces and cities

Requirements: When we register, there may be a situation of selecting a city. For example, when you select Hubei province for your province, the corresponding city will be automatically refreshed as the city below Hubei. Then how is the logic of the front page realized?

First find the label of the province element, and then send its value via $.post() to the Controller layer based on the.change event. The Controller layer returns the result (in XML or Json).

Here’s the first: The Controller layer connects to the front end page via XML

The Controller (servlet implementation)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //1. Int PIC = integer.parseInt (request.getParameter())"pic")); CityDao cityImpl = new cityDaoImpl(); List<city> findCity = cityImpl.findCity(pic); XStream =new XStream(); // Set the category name to xstream.alias("city", city.class); Xstream.useattributefor (city.class,"pic"); String xml = xstream.toXML(findCity); // Set the return format response.setContentType("text/xml; charset=utf-8"); response.getWriter().write(xml); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code

XStream XStream =new XStream(); Convert objects to XML form or XML to object format. Specific use to find a more detailed blog to write:

www.cnblogs.com/mengfanrong…

JS:

$(function(){//1. Find the province element and request the province element $("#province").change(functionVar PIC =$(this).val(); / / post request $. Post ("/AjaxAndJQuery/findCity",{pic:pic},function(data,status){// There is a data callback status for the returned value, 200 for OK // return an XML document, need the value of the <name> tag /* * <city PIC ="2"> <name> Huizhou </name> </city> <city PIC ="2"> <name> </name> </city>"#city").html(");
			$(data).find("city").each(function(){// execute the fuction method once through the city."city"//var PIC =$(this).children()"")
				var name=$(this).children("name").text(); //alert(name); // You can find $("#city").append("<option value=''>"+name);
			});
		});
	});
})
Copy the code

jsp:

<body> province: <select name="province" id="province">
		<option value="">- Please select - <option value="1"> <option value="2"> <option value="3"> <option value="4""> </select * from" <select name=""city" id="city">
		<option value="">- Please select - </select> </body>Copy the code

Mode 2: COntroller interacts with front-end page via Json

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

But since my example is written using servlets, that is, Json strings need to be assembled (either manually or via a utility class) JSONArray JSONArray = jsonArray.fromobject (findCity);

servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //1. Int PIC = integer.parseInt (request.getParameter())"pic")); CityDao cityImpl = new cityDaoImpl(); List<city> findCity = cityImpl.findCity(pic); JSONArray JSONArray = jsonArray.fromobject (findCity); String json = jsonArray.toString(); System.out.println(json); // Set the return format response.setContentType("text/html; charset=utf-8"); response.getWriter().write(json); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }}Copy the code

js:

$(function(){//1. Find the province element and request the province element $("#province").change(functionVar PIC =$(this).val(); / / post request $. Post ("/AjaxAndJQuery/findCityJson",{pic:pic},function(data,status){// There is a data callback for the status value returned, 200 for OK /** * return data is a json string * [{"name":"Guangzhou"."pic": 2}, {"name":"Shenzhen"."pic": 2}, {"name":"Huizhou"."pic": 2}, {"name":"Meizhou"."pic":2}] */ / delete the value of $("#city").html("); // go through the data, get the {} content in [], pass the city. $(data).each() {$(data).each();function(index,city){
	$("#city").append("<option value=''>"+city.name);
  	});
    },"json");
    });
})
Copy the code

The JSP: same as above