高手进:有关Ajax和Java Servlet的问题

fbchen 2007-03-24 12:29:08
1、页面引入prototype-1.5.1_rc2.js
<script language="JavaScript">
function sendText()
{
var url = "http://localhost:8080/test/testservlet?type=send";
var text = "myText:12345";
var request = new Ajax.Request(url, {
method: 'post',
asynchronous: true,
parameters: '',
postBody: text,
onFailure: sendFailed
});
}

function sendFailed(request)
{
alert("消息发送失败!");
}
</script>

2、TestServlet.java
public class TestServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GBK");
String type = request.getParameter("type");
String text = readRequestContent(request);
System.out.println("type=" + type);
System.out.println("text=" + text);
}

private String readRequestContent(HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {

}
return sb.toString();
}

}


结果打印:
type=send
text=

为什么没有取到postBody的内容呢??
分不够再加!
...全文
328 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
caibaoying 2007-04-02
  • 打赏
  • 举报
回复
来晚了``````````````恭喜了 接一分走人```
zuguanqun 2007-03-30
  • 打赏
  • 举报
回复
刚来,jf,恭喜
yuzm1984 2007-03-30
  • 打赏
  • 举报
回复
mark!!
emin_lee 2007-03-26
  • 打赏
  • 举报
回复
mark!
fbchen 2007-03-26
  • 打赏
  • 举报
回复
之前没有在servlet中读到,是因为Ajax.Request默认为“Content-type=application/x-www-form-urlencoded”。大家可以讨论一下,为什么没有读取到?要怎么样读取出来?
fbchen 2007-03-24
  • 打赏
  • 举报
回复
同志们,问题解决了
var request = new Ajax.Request(url, {
method: 'post',
asynchronous: true,
parameters: '',
postBody: text,
requestHeaders:["Content-type","text/plain;charset=GBK"],
onFailure: sendFailed
});
fbchen 2007-03-24
  • 打赏
  • 举报
回复
我不使用这个prototype.js,直接创建一个XMLHttpRequest,是可以发送的
现在可以确定问题就出在这个prototype.js里面!
healer_kx 2007-03-24
  • 打赏
  • 举报
回复
嗯,我还真的没有注意...那你就着重看你的方法吧...
fbchen 2007-03-24
  • 打赏
  • 举报
回复
readRequestContent是我定义的一个private方法
healer_kx 2007-03-24
  • 打赏
  • 举报
回复
String text = readRequestContent(request);
这句错了呗,更多就不知道了.

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧