一、前期页面准备:
1、添加struts框架,添加Action在struts-config.xml文件中配置好
2、在action中添加方法如:
(向页面传一组值)
public void testAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=gb2312"); PrintWriter out = response.getWriter(); String username=request.getParameter("username"); String password=request.getParameter("password"); //声明对象,向前台传值类似于map,前台通过: //var myobj=transport.responseText.evalJSON(true); //var isTrue=myobj.isTrue(键的名字); // 的到传过的值 JSONObject jsonObject=new JSONObject(); jsonObject.put("isTrue",false); if(username=="aa"||password=="aa"){ jsonObject.put("isTrue",true); out.print(jsonObject.toString()); out.flush(); out.close(); return; }else{ jsonObject.put("isTrue",false); out.print(jsonObject.toString()); out.flush(); out.close(); return; } } (向页面传单个值) public void testAjax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("application/json;charset=gb2312"); PrintWriter out = response.getWriter(); String username=request.getParameter("username"); String password=request.getParameter("password"); if(username=="aa"||password=="aa"){ out.print(true); out.flush(); out.close(); return; }else{ out.print(false); out.flush(); out.close(); return; } }
3、在页面中引用JS文件,如
<script type="text/javascript" src="js/prototype.js"></script>
二、页面向后台传一个form中的所有内容:
在页面中加入JS方法:如
(向后台传get方式的几个值)
function getStByKsKm(id,name){ var par="id="+id+"&name="+name; new Ajax.Request(//声明ajax对象 //调用方法名 'qxfp.do?method=getStByKsKm', { //*******传递单个少数几个值,用URL传递******** method:'get',//提交方式 method:'get',//提交方式 //*****传递多个值,用post方式******** method:'post',//提交方式 postBody: $('form1').serialize(),//序列化表单,即为发送表单做准备 onSuccess:function(response){//成功后执行的方法 //********成功以后用JSONObject得到后台传入的多个值********* //得到后台的返回的JSONObject对象 var myobj=response.responseText.evalJSON(true); //myobj的istrue字段中存储着结果 if(!myobj.istrue){ alert(myobj.errormessage); return; //********成功以后用得到后台传入的单个值********* var result=response.responseText; //result中存储着是后台的out.print();返回的值 if(result){ alert(myobj.errormessage); return; }} } } ); }
下篇日志是附带JS的代码: