日期:2014-05-18  浏览次数:20729 次

求高手指点ajax获得数据显示
Servlet中给出两个数据,String value0 = "1";String value1 = "2"; html中有两个文本框<input type = "text" id = "text1"> <input type = "text" id = "text2"> 请问如何通过ajax方式将value0放到text1中显示,将value1放到text2中显示。
 

------解决方案--------------------
在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];

} else{
alert('服务器错误');
}
}

}
------解决方案--------------------
struts2 + Jquery

1.创建封装这两个值的对象 且为User
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>


------解决方案--------------------
最简单就是不要传值过来,直接在后台进行html代码的编写,然后直接将html代码传过带javascript,