首先需要导入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" οnclick="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);
}
}