AJAX ,在jsp处理 action返回的不同数据类型

一,在action层

  设置返回的数据类型:

二,在jsp接受action传过来的数据

  解析相应的数据

 

例如

=======文本:输出文字

设置

response.setContentType("text/xml; charset=utf-8");  文本

PrintWriter out = response.getWriter();

out.print("欢迎测试");

out.close();

接收,解析

var info=xmlHttp.responseText;

 

======文本(把xml以字符串输出):更新城市列表

设置

response.setContentType("text/xml; charset=utf-8");  文本

PrintWriter out = response.getWriter();

StringBuffer buffer=new StringBuffer("<?xml version=\"1.0\" encoding=\"utf-8\" ?><result>");

buffer.append("<cityname cid='1'>");

buffer.append(“北京”);

buffer.append("</cityname>");

buffer.append("<cityname cid='2'>");

buffer.append(“上海”);

buffer.append("</cityname>");

buffer.append("</result>");

out.print(buffer.toString());

out.close();

接收,解析xml

function updateList(){

  clearList();

  var city=document.getElementById("city");

  var text = xmlHttp.responseText; 

  var xD=xmlHttp.responseXML;   

  if(xD){ //浏览器兼容,解析成dom树

    xD.loadXML(text);   

  }else{   //浏览器兼容,解析成dom树

    var oParser = new DOMParser();   

    xD= oParser.parseFromString(text,"text/xml");   

    //alert(xD.getElementsByTagName("a"));   

  } 

  var res=xD.getElementsByTagName("cityname");

  var option=null;

 

  for(i=0;i<res.length;i++){

    option=document.createElement("option");

    option.appendChild(document.createTextNode(res[i].firstChild.nodeValue));

    option.setAttribute("value",res[i].getAttribute('cid'));

    city.appendChild(option);

  }

}

 

======文本(把json以字符串输出):更新城市列表

设置

        PrintWriter out = response.getWriter();

        StringBuffer buffer = new StringBuffer("[");

buffer.append("{\"id\":\"1\",");   //格式要规范,变量名要双引号

buffer.append(",");

buffer.append("\"cityname\":\"北京\",");

buffer.append("\"provinceid\":北京市}");

buffer.append("]");

out.print(buffer.toString());

out.close();

接收,解析json

function updateList(){

     clearList();

     var city=document.getElementById("city");

     var res=eval(xmlHttp.responseText);  //eval 把字符串类型的脚本变成语句执行,这里转json

     var option=null;

 

  for(i=0;i<res.length;i++){

      option=document.createElement("option");

      option.appendChild(document.createTextNode(res[i].cityname));

      option.setAttribute("value",res[i].id);

      city.appendChild(option);

  }

}

======文本(把json以字符串输出):输出用户账号和密码列表

response.setContentType("text/xml; charset=UTF-8");

UserInfo user1=new UserInfo();

userInfo.setUserName("admin01");

userInfo.setPwd("adminpwd01");

UserInfo user2=new UserInfo("admin01", "adminpwd02");

List<UserInfo> list=new ArrayList<UserInfo>();

list.add(user1); list.add(user2);

JSONArray userList=JSONArray.fromObject(list);

out.print(userList);

out.close();

 

猜你喜欢

转载自4636.iteye.com/blog/2331701