本人菜鸟一只,今天瞎搞了一下Ajax没有成功,很多地方不明白,不知道哪里写错了,值一直传不到页面。求各位大哥指点迷津
Action
public class fuck extends ActionSupport{
@Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
PrintWriter out = response.getWriter();
System.out.println("-----------------");//为什么这个执行了,控制台却不会输出?
out.print(1); //这个值始终传不到页面。
out.flush();
out.close();
return SUCCESS;
}
}
HTML
<script type="text/javascript">
function CheckUser(){
req = new XMLHttpRequest();
alert("------");
req.open("post","/dcfs/denglu");
req.send();
req.onreadystatechange=req_onreadystatechange;
}
function req_onreadystatechange(){
if(req.readyState==4)
{
alert(req.readyState);
alert(req.responseText); //这里打印的是HTML页面的代码
}
}
</script>
</head>
<body>
<input type="button" id="but" name="but" value="Ajax测试" onclick="return CheckUser()"/>
</body>
Struts.XML
<package name="Album" namespace="/" extends="struts-default">
<action name="denglu" class="action.fuck">
<result name="success">/index.jsp</result>
</action>
</package>
ajax编程:
1.获得XMLHttpRequest对象
2.使用该对象向服务器发送请求
a.用get/post请求方式;
req.open("post",'/struts2_eg/dcfs/denglu',true);//这里请注意路径
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//post方法要加上:
b.注册监听器:当状态发生改变时调用处理函数:
req.onreadystatechange= function(){
if(req.readyState==4){
alert(req.responseText); //这里打印的是HTML页面的代码 namespace 加上 dcfs参考下面:
var xmlHttp = getRequest();
var url = "indexAction.jsp?date="+(new Date());
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
document.getElementById("hello").innerText = response;
}
};
xmlHttp.send(null);