JSON运用实例(Struts、JQuery、JSON三结合)

1.JSON所需的jar包

commons-logging.jar,
commons-lang.jar,
commons-collections.jar,
json.jar,
commons-beanUtils.jar,
ezmorph.jar

 

2.页面相关

<%String path = request.getContextPath();%>

 

<script language="javascript" src="<%=path%>/js/jquery-1.2.6.js"></script>

 

<script language="JavaScript">
   function update(v1,v2){
       var param = {type:v1,face:v2};
    //请求数据
    $.ajax({  
              url:'<%=path%>/t.do?method=update',  
              data:param,//{type:'01',account:'11'},
              dataType:'json', //服务器返回的数据类型  
              error:function(){  
                  alert("服务器忙,请稍后重试!");  
              },  
              success:function(result){
                  alert(result.name + "," + result.sex + "," + result.age);
               }
          });
   }
</script>

 

<input type="button" onclick="update('ok','hehe');" value="用Jquery发送Json请求">

 

3.Action相关

public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setHeader("Cache-Control", "no-cache"); response.setContentType("text/json;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); System.out.println("接收到的参数:type=" + request.getParameter("type") + ", face=" + request.getParameter("face")); User user = new User(); user.setName("雾非雾"); user.setSex("男"); user.setAge(24); JSONObject json = JSONObject.fromObject(user); response.getWriter().write(json.toString()); return null; }

你可能感兴趣的:(JavaScript,jquery,json,exception,function,struts)