问题描述
- 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,
解决方案
http://blog.csdn.net/rushkid02/article/details/7506787
解决方案二:
根本你就没传参数,user没传
解决方案三:
我看懂了。
我想省略写
还是应该写个变量
infor="id"+user;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 前面再加个这个
xhr.send(infor);