当前位置:首页 > Web开发 > 正文

" );$( "#show").append("成绩:" + data.score+"

2024-03-31 Web开发

Struts2整合AJAX有2种方法:

使用type="stream"类型的<result>

使用JSON插件

使用type="stream"类型的<result>  获取text 前端

<body> <form> 学号:<input type="text"><br /> 姓名:<input type="text"><br /> <button type="button">盘问成效</button> </form> <p></p> <script src="http://www.mamicode.com/js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"HandlerAction", type:"get", data:{"no":$("#no").val(),"name":$("#name").val()}, dataType:"text", error:function () { console.log("ajax请求掉败!") }, success:function (data) { $("#score").text(data); } }) }); </script> </body>

url要和struts.xml中action的name、包的namespace对应。

action

public class HandlerAction extends ActionSupport { private int no; private String name; private InputStream inputStream; public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public InputStream getInputStream() { return inputStream; } public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } @Override public String execute() throws Exception { //此处缺省连接数据库盘问总分 String result = name + "同学,你的总分是:680"; //设置要返回的数据。我们传给浏览器的数据含有中文,需要设置utf-8编码,来解决中文乱码 inputStream=new ByteArrayInputStream(result.getBytes("utf-8")); return SUCCESS; } }

前端向后台发送了2个字段:no、name

action需要设置2个同名的成员变量,并供给对应的getter、setter要领,才华接收到前端传来的数据。

需要一个InputStream类型的成员变量,并供给对应的getter、setter,用于向浏览器返回数据。

需要一个措置惩罚惩罚请求的要领(execute),设置返回给浏览器的数据。

struts.xml

<struts> <package namespace="http://www.mamicode.com/" extends="struts-default"> <action class="action.HandlerAction"> <result type="stream"> <!-- 设置返回给浏览器的数据类型 --> <param>text/html</param> <!--指定获取InputStream的要领,getInputStream(),约定:去失get,后面部分使用camel写法 --> <param>inputStream</param> </result> </action> </package> </struts>

流程分析

前端向后台发送ajax请求,通报no、name2个字段

JVM创建action实例,挪用no、name对应的setter要领把前端传过来的值赋给成员变量(会自动转换为方针类型),完成action的初始化

JVM挪用action措置惩罚惩罚业务的要领execute,设置向浏览器返回的数据

JVM按照struts.xml中<result>指定的要领(getInputStream),获取InputSteam,将里面的数据传给浏览器。

使用type="stream"类型的<result>  获取json 前端

<body> <form> 学号:<input type="text"><br /> <button type="button">盘问学生信息</button> </form> <div></div> <script src="http://www.mamicode.com/js/jquery-3.4.1.min.js"></script> <script> $("#btn").click(function () { $.ajax({ url:"HandlerAction", type:"post", data:{"no":$("#no").val()}, dataType:"json", error:function () { console.log("ajax请求掉败!") }, success:function (data) { $("#show").append("姓名:" + data.name+","); $("#show").append("春秋:" + data.age+","); $("#show").append("成效:" + data.score+"。"); } }) }); </script> </body>

action

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/32812.html