在JSP中運用 Ajax
阿新 • • 發佈:2019-02-11
首先編寫JS部分程式碼
JavaScript方式
..已經忘記了。。jQuery方式
其實有JQuery方式完全沒人用javaScript方式演示程式碼:點選一個 按鈕,傳遞過去一個 age=25 ,再返回回來兩個。
JS部分
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <input type="text" id="my-content"><input type="button" value="點選" onclick="start();"> </body> <script type="text/javascript" src="js/jquery-3.2.1.js"></script> <script type="text/javascript" > /* /servlet/Test2 */ function start(){ var content=$("#my-content").val(); $.ajax({ url:'servlet/Test3', type:'POST', //GET async:true, //或false,是否非同步 data:{ name:'yang',age:25//想要傳輸過去的資料 key:value,另一個頁面通過 key接收value的值 }, timeout:5000, //超時時間 dataType:'text', //返回的資料格式:json/xml/html/script/jsonp/text success:function(data,textStatus,jqXHR){//data是成功後,接收的返回值 console.log(data); console.log(textStatus); console.log(jqXHR); $("#my-content").val(data);//將返回成功的值展示到input裡 } }); } </script> </html>
Java部分程式碼
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); String age=request.getParameter("age");//接收Ajax傳過來的值 PrintWriter out = response.getWriter();//新建一個out物件 //把他輸出就相當於把資料返回了。 //write 與 print 不同,必須是手動把資料裝換成String型別 out.write(String.valueOf((age+age))); }
如果是JSON資料的話記住封裝與解析。
var last=JSON.stringify(obj); //將JSON物件轉化為JSON字元
alert(last);
使用這個方法在html頁面驗證資料