在servlet中: PrintWriter out=response.getWriter(); out.print(value0+","+value1); 在jsp页面:(前面加浏览器判断) var xmlHttp=new XMLHttpRequest(); function ajaxParam(){ var name=document.getElementById("uname").value; var pwd=document.getElementById("upwd").value;
//get请求方式 xmlHttp.open("get", "<%=path%>/AjaxSvlt", true); xmlHttp.onreadystatechange=toBack; xmlHttp.send(null); }function toBack(){ if(xmlHttp.readyState==4){ if(xmlHttp.status==200){ var rspsText = xmlHttp.responseText; var arr=rspsText.split(","); document.getElementById("text1").innerHTML=arr[0]; document.getElementById("text2").innerHTML=arr[2];
还是找点ajax的实用场景来做练习吧。
out.print(value0+","+value1);
在jsp页面:(前面加浏览器判断)
var xmlHttp=new XMLHttpRequest();
function ajaxParam(){
var name=document.getElementById("uname").value;
var pwd=document.getElementById("upwd").value;
//get请求方式
xmlHttp.open("get", "<%=path%>/AjaxSvlt", true);
xmlHttp.onreadystatechange=toBack;
xmlHttp.send(null);
}function toBack(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var rspsText = xmlHttp.responseText;
var arr=rspsText.split(",");
document.getElementById("text1").innerHTML=arr[0];
document.getElementById("text2").innerHTML=arr[2];
} else{
alert('服务器错误');
}
}
}
private String value_;
getter,setter;
.....2. Action方法(需要添加net.sf.json包): private String jsonRes;
//getter,setter..public String testAction() {
List<User> objList = new ArrayList();
objList.add(this.user);
User us1 =new User(); //传值对象
us.setValue("1");
User us2 =new User();
us.setValue("2");
objList.add(us1);
objList.add(us2); //将两个对象添加进列表,以便前台获取 JSONArray array = JSONArray.fromObject(objList);
this.jsonRes=array.toString();
return "success";
}2.struts.xml <package name="ajax" extends="json-default"> <action name="testAction" class="..." method="testAction">
<result type="json">
<!-- 指定返回结果,将结果保存在root域中,以便前台获取,root不能修改为其他名字,否则将不能返回 -->
<param name="root">
jsonRes
</param>
</result>
</action>
3.页面:
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
//表单提交出发
function testPost(){
//AJAX访问后台方法,验证用户名
$.ajax( {
url : "testAction.action", // 指向处理Action
type : "post", // 数据发送方式
dataType : "json", // 接受数据格式
data : params, // 要传递的数据
success : update_page // 回传函数
});
}
function update_page(jsonRes) { //处理AJAX返回结果,用于显示
var json = eval("(" + jsonRes + ")");
$("#text1").val(json[0].value_);
$("#text2").val(json[1].value_);
}
</script><body>
<input type = "text" id = "text1">
<input type = "text" id = "text2"> <s:form method="post" >
<input type="button" id="submit" value="提交" onclick="testPost()" />
</s:form></body>