日期:2014-05-16  浏览次数:20800 次

Servlet无法获取ajax传过来的参数 - Web 开发 / Ajax
最近在学ajax,做了个demo,发现servlet无法取得send传过来的参数,代码片断如下:
index.jsp:
<script type="text/javascript">
function submit() {
var id = document.forms[0].id.value;
var xmlhttp;
  ...
xmlhttp.open("GET", "ShowBalance", true); //用get将参数传递给servlet
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("id="&id);
}
</script>
</head>
<body>
<form>
<input type="text" name="id" id="id" />
<input type="submit" name="submit" id="submit" onclick="submit();" value="Submit" />
</form>
</body>

web.xml:
<servlet-mapping>
<servlet-name>ShowBalance</servlet-name>
<url-pattern>/ShowBalance</url-pattern>
</servlet-mapping>

ShowBalance.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("id")); //在控制台上没有输出id
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("ajax demo");
}

提交后地址栏里的值:http://localhost:8080/ajaxdemo/?id=2154&submit=Submit,似乎没有转到servlet。

环境:eclipse3.3.1 tomcat5.5

请各位前辈帮我看看。

------解决方案--------------------
<input type="submit" name="submit" id="submit" onclick="submit();" value="Submit" />

改成

<input type="button" name="submit" id="submit" onclick="submit();" value="Submit" />


------解决方案--------------------
我看你是没搞清楚ajax的get和post方法

get的话你要把参数加到url后面
post的话需要用调用ajaxobj.send来发送