kjwangxun
2016-01-11 14:41
采纳率: 69.2%
浏览 2.1k
已采纳

ajax传值,servlet得到为空

js代码:
var xhr = getXhr();
function getXhr(){
var xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xhr = false;
}
}
}
if (!xhr) {
alert("err Happend!");
}
return xhr;
}
function check() {
var user = document.getElementById("user").value;
var url = "RegisterServlet";
if (xhr.readyState == 4 && xhr.status == 200) {
var str = xhr.responseText;
document.getElementById("checkname").innerHTML=str;
}
xhr.open('post',url,true);
alert(user);
xhr.send("id"+user);
}
servlet代码:
package com.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Dao.LoginDao;
import com.Model.Login;

public class RegisterServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

    response.setContentType("text/html");
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    PrintWriter out = response.getWriter();
    String username=request.getParameter("id");
    System.out.println(username);
    LoginDao dao=new LoginDao();
    boolean mark=dao.RegisterCheck(username);
    System.out.println(mark);
    if(mark==true){
        out.println("用户名重复");
        System.out.println("用户名重复");
    }else if(mark==false){
        out.println("用户名可用");
        System.out.println("用户名可用");
    }
}

}
只截取了ajax传值部分,还有登陆的验证也写在doPost里先删了,
之前用get方法能行,改成post就出问题了;
大神帮看看,js里能得到user的值,servlet得到ajax传来的user值为null,

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • threenewbee 2016-01-11 14:50
    已采纳
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 咸池 2016-01-11 15:00

    根本你就没传参数,user没传

    评论
    解决 无用
    打赏 举报
  • kjwangxun 2016-01-11 15:10

    我看懂了。
    我想省略写
    还是应该写个变量
    infor="id"+user;
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 前面再加个这个
    xhr.send(infor);

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题