咱們可使用前端的一個標籤來僞造一個ajax的樣子。iframe標籤javascript
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax初體驗</title> <script> function f() { //獲取url框的value即url var url = document.getElementById("url").value; //將獲取到的url賦值給iframe的屬性src document.getElementById("iframe").src=url; } </script> </head> <body> <div> <p>請輸入地址:</p> <input type="url" id="url"> <!--onclick 按下按鈕發生的事件--> <input type="button" id="button" value="提交" onclick="f()"> </div> <div> <iframe id="iframe" style="width: 100%;height: 500px" ></iframe> </div> </body> </html>
測試:url中輸入嗶哩嗶哩的網址,點擊提交按鈕css
jQuery.ajax(...) 部分參數: url:請求地址 type:請求方式,GET、POST(1.9.0以後用method) headers:請求頭 data:要發送的數據 contentType:即將發送信息至服務器的內容編碼類型(默認: "application/x-www-form-urlencoded; charset=UTF-8") async:是否異步 timeout:設置請求超時時間(毫秒) beforeSend:發送請求前執行的函數(全局) complete:完成以後執行的回調函數(全局) success:成功以後執行的回調函數(全局) error:失敗以後執行的回調函數(全局) accepts:經過請求頭髮送給服務器,告訴服務器當前客戶端課接受的數據類型 dataType:將服務器端返回的數據轉換成指定類型 "xml": 將服務器端返回的內容轉換成xml格式 "text": 將服務器端返回的內容轉換成普通文本格式 "html": 將服務器端返回的內容轉換成普通文本格式,在插入DOM中時,若是包含JavaScript標籤,則會嘗試去執行。 "script": 嘗試將返回值看成JavaScript去執行,而後再將服務器端返回的內容轉換成普通文本格式 "json": 將服務器端返回的內容轉換成相應的JavaScript對象 "jsonp": JSONP 格式使用 JSONP 形式調用函數時,如 "myurl?callback=?" jQuery 將自動替換 ? 爲正確的函數名,以執行回調函數
咱們進行一個簡單的測試,使用最原始的HttpServletRequest處理1html
web.xml前端
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--關聯一個SpringMVC的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--服務器啓動的時候就啓動--> <load-on-startup>1</load-on-startup> </servlet> <!-- / 匹配全部的請求 不包括.jsp /* 匹配全部的請求 包括.jsp --> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
springmvc-servlet.xmljava
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--掃描包配置,控制層,和前端交互 controller--> <context:component-scan base-package="com.star.controller"/> <!--開啓註解掃描--> <mvc:annotation-driven/> <!--靜態資源過濾--> <mvc:default-servlet-handler/> <!--添加視圖解析器--> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
package com.star.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController public class ajaxController { @RequestMapping("/t1") public void test2(String name, HttpServletResponse response) throws IOException { System.out.println("test2:param=>" + name); if ("lenStar".equals(name)){ response.getWriter().print("true"); }else{ response.getWriter().print("false"); } } }
可以使用在線的CDN,也能夠下載導入;jquery
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script> <script> function a(){ $.post({ url:"${pageContext.request.contextPath}/t1", data:{"name":$("#username").val()},//這裏的data是傳給後端的值 success:function (data,status) { //這裏的data是後臺傳來的數據 console.log(data); console.log(status) } }); } </script> </head> <body> <%--失去焦點的時候發起一個請求(攜帶信息)到後臺--%> 用戶名:<input type="text" id="username" onblur="a()"> </body> </html>
打開瀏覽器的控制檯,當咱們鼠標離開輸入框的時候,能夠看到發出來一個ajax的請求!是後臺返回給咱們的結果!web
輸入lenStar時:ajax
package com.star.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
@RequestMapping("/t2") public List<User> test3(){ List<User> users = new ArrayList<User>(); users.add(new User("張三",2,"男")); users.add(new User("李四",3,"女")); users.add(new User("王五",4,"男")); users.add(new User("趙六",5,"女")); return users; }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script> <script> $(function () { $("#btn").click(function () { $.post("${pageContext.request.contextPath}/t2", function (data) { console.log(data); var html =""; for (let 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> </head> <body> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small>用戶列表 —— 顯示全部用戶信息</small> </h1> </div> </div> </div> <div class="row"> <div class="col-md-4 column"> <input class="btn btn-primary" id="btn" type="button" value="加載數據"> </div> </div> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-hover table-striped"> <thead> <tr> <th>姓名</th> <th>年齡</th> <th>性別</th> </tr> </thead> <tbody id="content"> </tbody> </table> </div> </div> </div> </body> </html>
咱們平時註冊時候,輸入框後面的實時提示怎麼作到的;如何優化?spring
@RequestMapping("/t3") public String test4(String name,String pwd){ String msg=""; if(name!=null){ if("lenStar".equals(name)){ msg = "OK!"; }else { msg = "用戶名錯誤!"; } } if(pwd!=null){ if("123456".equals(pwd)){ msg = "OK!"; }else { msg = "密碼錯誤!"; } } return msg; }
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script> <script> function a1() { $.post({ url:"${pageContext.request.contextPath}/t3", data:{"name":$("#name").val()}, success:function (data) { if(data.toString()==="OK!"){ $("#nameInfo").css("color","green") }else { $("#nameInfo").css("color","red") } $("#nameInfo").html(data) } }) } function a2() { $.post({ url:"${pageContext.request.contextPath}/t3", 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> <div class="container"> <div class="row clearfix"> <div class="col-md-12 column"> <div class="page-header"> <h1> <small style="padding-left: 400px">用戶登陸頁面</small> </h1> </div> </div> </div> <form style="padding-left: 300px" class="form-horizontal" role="form"> <div class="form-group"> <label class="col-sm-2 control-label">用戶名</label> <div class="col-sm-10"> <input type="text" id="name" class="form-control" style="width: 300px" placeholder="請輸入用戶名" onblur="a1()"> <span id="nameInfo"></span> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">密碼</label> <div class="col-sm-10"> <input type="password" class="form-control" style="width: 300px" id="pwd" placeholder="請輸入密碼" onblur="a2()"> <span id="pwdInfo"></span> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox"> 記住我 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button style="width: 300px" type="submit" class="btn btn-primary">登陸</button> </div> </div> </form> </div> </body> </html>
輸入不正確時:數據庫
輸入正確時:
**動態請求響應,局部刷新,就是如此!