首先需要匯入jQuery.js 百度jQuery進官網下載就行 注意要放在 WEB-INF下面
前端代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="/ajax/js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function ajaxFun(){
$.ajax({
type: "POST", //傳資料的方式
url: "TestServlet", //servlet地址
data: $('#form').serialize(), //傳的資料 form表單 裡面的資料
success: function(result){ //傳資料成功之後的操作 result是servlet傳過來的資料 這個函數對result進行處理,讓它顯示在 輸入框中
$("#result").val(result); //找到輸入框 並且將result的值 傳進去
}
});
}
</script>
</head>
<body>
<H1 align="center">請輸入兩個字串</H1>
<div align="center">
<form id="form">
first:<input type="text" name="first" id="first">
second:<input type="text" name="second" id="second">
<button type="button" onclick="ajaxFun()">button</button> //提交 按鈕
</form>
<input type="text" id="result"> // 用來 顯示 result
</div>
</body>
</html>
servlet代碼:
package ajax;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class TestServlet extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String first = request.getParameter("first"); //從前端擷取資料first
String second = request.getParameter("second");//從前端擷取資料second
String result=first+second;
System.out.println(result); //用於測試 ,判斷是否成功擷取到資料;
out.println(result); //將資料傳到前端
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}