关于Java Ajax 为什么后台有返回值,但是js接收到之后就什么都没有了?
js代码$("#userid").focusout(function(){varuserid=$("#userid").val();varmsg=document.get...
js代码
$("#userid").focusout(function (){
var userid = $("#userid").val();
var msg = document.getElementById("userid_msg");
$.ajax({
url:"UserServlet?userid=" + userid,
type:"GET",
dataType:"json",
success:function(data){
alert(data);
console.log(data);
if (data != "no"){
msg.innerHTML = "存在的用户名!userid=" + data.userid;
} else {
msg.innerHTML = "用户名不存在!";
}
}
})
})
Java后台代码
数据库操作:
public User findById(String userid) throws SQLException{
ResultSet rs = null;
User vo = null;
String sql = "SELECT userid,password FROM user WHERE userid=?";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1, userid);
rs = this.pstmt.executeQuery();
if (rs.next()){
vo = new User();
vo.setUserid(rs.getString(1));
vo.setPassword(rs.getString(2));
}
return vo;
}
}
Servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userid = request.getParameter("userid");
try {
User vo = new UserDB(new DBConnection().getConnection()).findById(userid);
if (vo == null) {
response.getWriter().println("no");
} else {
StringBuffer json = new StringBuffer();
json.append("{\"userid\":\"");
json.append(vo.getUserid() + "\"}");
response.getWriter().println(json.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
} 展开
$("#userid").focusout(function (){
var userid = $("#userid").val();
var msg = document.getElementById("userid_msg");
$.ajax({
url:"UserServlet?userid=" + userid,
type:"GET",
dataType:"json",
success:function(data){
alert(data);
console.log(data);
if (data != "no"){
msg.innerHTML = "存在的用户名!userid=" + data.userid;
} else {
msg.innerHTML = "用户名不存在!";
}
}
})
})
Java后台代码
数据库操作:
public User findById(String userid) throws SQLException{
ResultSet rs = null;
User vo = null;
String sql = "SELECT userid,password FROM user WHERE userid=?";
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1, userid);
rs = this.pstmt.executeQuery();
if (rs.next()){
vo = new User();
vo.setUserid(rs.getString(1));
vo.setPassword(rs.getString(2));
}
return vo;
}
}
Servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userid = request.getParameter("userid");
try {
User vo = new UserDB(new DBConnection().getConnection()).findById(userid);
if (vo == null) {
response.getWriter().println("no");
} else {
StringBuffer json = new StringBuffer();
json.append("{\"userid\":\"");
json.append(vo.getUserid() + "\"}");
response.getWriter().println(json.toString());
}
} catch (SQLException e) {
e.printStackTrace();
}
} 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询