current position:Home>Spring mvc07: Ajax research

Spring mvc07: Ajax research

2022-04-29 13:28:30Duan Xuechang

brief introduction

AJAX = Asynchronous JavaScript and XML( Asynchronous JavaScript and XML).
AJAX It's a way to do this without reloading the entire web page , Technology to update some web pages .
Ajax It's not a new programming language , It's a way to create better, faster, more interactive Web Application Technology .
stay 2005 year ,Google Through its Google Suggest send AJAX Become popular .Google Suggest Can automatically help you complete the search word .
Google Suggest Use AJAX Create dynamic web Interface : When you type a keyword into Google's search box ,JavaScript These characters will be sent to the server , Then the server will return a list of search suggestions .
Just like the search box of Baidu in China !
Traditional web pages ( That is not to say ajax Technology web page ), Want to update content or submit a form , You need to reload the entire page .
Use ajax Technology web page , Through a small amount of data exchange in the background server , You can achieve asynchronous local update .
Use Ajax, Users can create direct applications close to the local desktop 、 High availability 、 Richer 、 More dynamic Web The user interface .

forge Ajax

We can use a label on the front end to forge a ajax The appearance of .iframe label
1、 Create a new one module :sspringmvc-06-ajax , Import web Support !
2、 Write a ajax-frame.html Use iframe test , Feel the effect

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="UTF-8">
   <title>kuangshen</title>
</head>
<body>

<script type="text/javascript"> window.onload = function(){
       var myDate = new Date(); document.getElementById('currentTime').innerText = myDate.getTime(); }; function LoadPage(){
       var targetUrl = document.getElementById('url').value; console.log(targetUrl); document.getElementById("iframePosition").src = targetUrl; } </script>

<div>
   <p> Please enter the address to load :<span id="currentTime"></span></p>
   <p>
       <input id="url" type="text" value="https://www.baidu.com/"/>
       <input type="button" value=" Submit " onclick="LoadPage()">
   </p>
</div>

<div>
   <h3> Load page location :</h3>
   <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>

</body>
</html>

3、 Use IDEA Open a browser and test it !

utilize AJAX You can do it :

Registration time , Enter the user name to automatically detect whether the user already exists .
Landing time , Prompt user name password error
When deleting a data row , Put lines ID Send to background , Background delete in database , After the database is deleted successfully , On the page DOM Delete the data row as well .
… wait

jQuery.ajax

pure JS Native implementation Ajax We're not going to explain here , Use it directly jquery Provided , Easy to learn and use , Avoid making wheels repeatedly , Interested students can go to understand JS Native XMLHttpRequest !
Ajax The core is XMLHttpRequest object (XHR).XHR Provides an interface for sending requests to the server and parsing server responses . Ability to get new data from the server asynchronously .
jQuery Provide more than one with AJAX Related methods .
adopt jQuery AJAX Method , You can use HTTP Get and HTTP Post Request text from a remote server 、HTML、XML or JSON – At the same time, you can load the external data directly into the selected elements of the web page .
jQuery It's not the producer , It's nature porters .
jQuery Ajax Nature is XMLHttpRequest, It's encapsulated , Convenient to call !

jQuery.ajax(...)
       Some parameters :
            url: Request address 
            type: Request mode ,GET、POST(1.9.0 After use method)
        headers: Request header 
            data: Data to send 
    contentType: The type of content encoding to send the message to the server ( Default : "application/x-www-form-urlencoded; charset=UTF-8")
          async: Asynchronous or not 
        timeout: Set request timeout ( millisecond )
      beforeSend: Function executed before sending the request ( overall situation )
        complete: Callback function executed after completion ( overall situation )
        success: Callback function executed after success ( overall situation )
          error: Callback function executed after failure ( overall situation )
        accepts: Send the request to the server , Tells the server what data types are acceptable to the current client 
        dataType: Convert the data returned by the server to the specified type 
          "xml":  Convert the content returned by the server to xml Format 
          "text":  Convert the content returned by the server to normal text format 
          "html":  Convert the content returned by the server to normal text format , In the insert DOM In the middle of the day , If you include JavaScript label , Then they try to execute .
        "script":  Try to treat the return value as JavaScript To carry out , Then the content returned by the server is converted to normal text format 
          "json":  Convert the content returned by the server to the corresponding JavaScript object 
        "jsonp": JSONP  Format use  JSONP  When a function is called in form , Such as  "myurl?callback=?" jQuery  Will be replaced automatically  ?  Is the correct function name , To execute a callback function 

Let's take a simple test , Use the most primitive HttpServletResponse Handle , . The most simple , Most common
1、 To configure web.xml and springmvc Configuration file for , Just copy the above case 【 Remember static resource filtering and annotation driven configuration 】

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

   <!--  Automatically scan the specified package , All of the following annotation classes are given to IOC Container management  -->
   <context:component-scan base-package="com.kuang.controller"/>
   <mvc:default-servlet-handler />
   <mvc:annotation-driven />

   <!--  view resolver  -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
       <!--  Prefix  -->
       <property name="prefix" value="/WEB-INF/jsp/" />
       <!--  suffix  -->
       <property name="suffix" value=".jsp" />
   </bean>

</beans>

2、 Write a AjaxController

@Controller
public class AjaxController {
    

   @RequestMapping("/a1")
   public void ajax1(String name , HttpServletResponse response) throws IOException {
    
       if ("admin".equals(name)){
    
           response.getWriter().print("true");
      }else{
    
           response.getWriter().print("false");
      }
  }

}

3、 Import jquery , You can use online CDN , You can also download and import

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>

4、 To write index.jsp test

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
  <%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
   <script> function a1(){
       $.post({
       url:"${pageContext.request.contextPath}/a1", data:{
      'name':$("#txtName").val()}, success:function (data,status) {
       alert(data); alert(status); } }); } </script>
 </head>
 <body>
<%--onblur: Loss of focus triggers the event --%>
 user name :<input type="text" id="txtName" onblur="a1()"/>
 </body>
</html>

5、 start-up tomcat test ! Open the browser's console , When we leave the input box with the mouse , You can see that a ajax Request ! It's the result of the background back to us ! Test success !

Springmvc Realization

Entity class user

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    

   private String name;
   private int age;
   private String sex;

}

Let's get a collection object , Show to front page

@RequestMapping("/a2")
public List<User> ajax2(){
    
   List<User> list = new ArrayList<User>();
   list.add(new User(" Qinjiang 1 Number ",3," male "));
   list.add(new User(" Qinjiang 2 Number ",3," male "));
   list.add(new User(" Qinjiang 3 Number ",3," male "));
   return list; // because @RestController annotation , take list Turn into json Format return 
}

Front page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<input type="button" id="btn" value=" get data "/>
<table width="80%" align="center">
   <tr>
       <td> full name </td>
       <td> Age </td>
       <td> Gender </td>
   </tr>
   <tbody id="content">
   </tbody>
</table>

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script> $(function () {
       $("#btn").click(function () {
       $.post("${pageContext.request.contextPath}/a2",function (data) {
       console.log(data) var html=""; for (var i = 0; i <data.length ; i++) {
       html+= "<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].age + "</td>" + "<td>" + data[i].sex + "</td>" + "</tr>" } $("#content").html(html); }); }) }) </script>
</body>
</html>

The data echo is realized successfully ! You can experience Ajax The benefits of !

Registration prompt effect

Let's test a little Demo, Think about it when we register , The real-time prompt behind the input box is how to do it ; How to optimize
Let's write a Controller

@RequestMapping("/a3")
public String ajax3(String name,String pwd){
    
   String msg = "";
   // There is data in the simulation database 
   if (name!=null){
    
       if ("admin".equals(name)){
    
           msg = "OK";
      }else {
    
           msg = " User name input error ";
      }
  }
   if (pwd!=null){
    
       if ("123456".equals(pwd)){
    
           msg = "OK";
      }else {
    
           msg = " Wrong password input ";
      }
  }
   return msg; // because @RestController annotation , take msg Turn into json Format return 
}

Front page login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>ajax</title>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
   <script>

       function a1(){
    
           $.post({
    
               url:"${pageContext.request.contextPath}/a3",
               data:{
    'name':$("#name").val()},
               success:function (data) {
    
                   if (data.toString()=='OK'){
    
                       $("#userInfo").css("color","green");
                  }else {
    
                       $("#userInfo").css("color","red");
                  }
                   $("#userInfo").html(data);
              }
          });
      }
       function a2(){
    
           $.post({
    
               url:"${pageContext.request.contextPath}/a3",
               data:{
    'pwd':$("#pwd").val()},
               success:function (data) {
    
                   if (data.toString()=='OK'){
    
                       $("#pwdInfo").css("color","green");
                  }else {
    
                       $("#pwdInfo").css("color","red");
                  }
                   $("#pwdInfo").html(data);
              }
          });
      }

   </script>
</head>
<body>
<p>
   user name :<input type="text" id="name" onblur="a1()"/>
   <span id="userInfo"></span>
</p>
<p>
   password :<input type="text" id="pwd" onblur="a2()"/>
   <span id="pwdInfo"></span>
</p>
</body>
</html>

【 Remember to deal with json The code problem 】
Test it out , Dynamic request response , Partial refresh , That's all. !
 Insert picture description here
obtain baidu Interface Demo

<!DOCTYPE HTML>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>JSONP Baidu search </title>
   <style> #q{
       width: 500px; height: 30px; border:1px solid #ddd; line-height: 30px; display: block; margin: 0 auto; padding: 0 10px; font-size: 14px; } #ul{
       width: 520px; list-style: none; margin: 0 auto; padding: 0; border:1px solid #ddd; margin-top: -1px; display: none; } #ul li{
       line-height: 30px; padding: 0 10px; } #ul li:hover{
       background-color: #f60; color: #fff; } </style>
   <script> // 2. Step two  //  Definition demo function  ( Analysis interface 、 data ) function demo(data){
       var Ul = document.getElementById('ul'); var html = ''; //  If the search data exists   Add content  if (data.s.length) {
       //  Hidden ul Show it  Ul.style.display = 'block'; //  The searched data loop is appended to li in  for(var i = 0;i<data.s.length;i++){
       html += '<li>'+data.s[i]+'</li>'; } //  Cyclic li write in ul Ul.innerHTML = html; } } // 1. Step one  window.onload = function(){
       //  Get the input box and ul var Q = document.getElementById('q'); var Ul = document.getElementById('ul'); //  Event when the mouse is up  Q.onkeyup = function(){
       //  If the input box is not empty  if (this.value != '') {
       // ******************JSONPz a key ******************** //  Create a label  var script = document.createElement('script'); // Given the address to cross domain   Assign a value to src // Here is the cross domain address to request   I wrote the cross domain address of Baidu search  script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo'; //  Put the combined belt src Of script The tag is appended to body in  document.body.appendChild(script); } } } </script>
</head>

<body>
<input type="text" id="q" />
<ul id="ul">

</ul>
</body>
</html>

Ajax It is very important in our development , Be sure to learn how to use !
Meet the madman and say
Welcome to join me for wechat exchange and discussion ( Please note csdn Add )
 Insert picture description here

copyright notice
author[Duan Xuechang],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291116495612.html

Random recommended