首先我的代码:
$(document).ready(function(){
$('#button').click(function(){
$.post(
'Servlet',
{
name:$("#name").val(),
password:$("#password").val()
},
function(data,status) {
if(status=="success")
{
var i=5;
setInterval(function(){
alert("欢迎"+data.name+"成功注册,"+i--+"秒后进入登陆界面");
},1000);
window.location.href="index.html";
}
}
)
});
});
这是正确之后传值成功的版本,之前错误的版本是要传信息写成一个var dat= new Array(); 然后给这个数组赋值,发现传是传过去了,但是servlet根本没有获取到我的值,很生气 试了好久,发现这种传数组的方式好像是不对的,所以改成了上图,传值成功了。
package Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Bean.Bean;
import Sql.Sql;
/**
* Servlet implementation class Servlet
*/
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Servlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
Bean bean=new Bean();
String name = request.getParameter("name");
String password =request.getParameter("password");
System.out.println(name);
System.out.println(password);
bean.setName(name);
bean.setPassword(password);
Sql sql=new Sql();
boolean a=sql.select(bean);
if(a==true)
{
out.println("{name:'"+name+"',password:'"+password+"'}");
}
else {
}
// response.getWriter().append("Served at: ").append(request.getContextPath());
//
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
Bean bean=new Bean();
String name = request.getParameter("name");
String password =request.getParameter("password");
bean.setName(name);
bean.setPassword(password);
Sql sql=new Sql();
sql.insert(bean);
out.println("{name:'"+name+"',password:'"+password+"'}");
}catch(Exception e) {
e.printStackTrace();
}
doGet(request, response);
}
}
如何接收到值如上图的方式
String name = request.getParameter("name");
String password =request.getParameter("password");
而且你一定要写这一部分
out.println("{name:'"+name+"',password:'"+password+"'}");
这一部分属于给Ajax返回值的部分不然的话,会出现前端Ajax错误,到时候前端咋找也找不到错,其实是后端的原因。后续我会把这整个项目贴上来。