关于ajax的学习

这里用struts2框架搭建的环境,中间的配置文件web.xml,struts.xml,和动态方法调用没有列出,知识为了总结ajax的一个前后台数据交互的过程。

1.前端页面:放一个按钮(一定记得把jQuery引进jsp页面)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <%-- <base href="<%=basePath%>"> --%>
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <!-- 引入jQuery -->
    <script type="text/javascript" language="javascript" src="<%=basePath%>/js/jquery-1.3.1.js"></script>

    $(document).ready(function(){
    var $oDiv = $("#ajax");
    $oDiv.click(function(){

       $.ajax({
            type:"GET",//发送请求类型
            url:"user!add",//请求路径
            //async:false,//默认为true,是异步请求
            //传参给后台的形式(两种方式)
            //data:{"username":"test","password":"123456"},
            data:"username=test&password=123456",
            dataType:"script",//返回类型
            cache: false,//不使用当前浏览器的缓存
            success:function(msg){//请求成功后调用的回调函数
                //请求成功
                alert("msg="+msg);
                alert("success");
            },
            error:function(){
                //Exception
                alert("error");
            }
        });

   });
});

</head>
         
  <body>
    <input  id="ajax" type="button" value="添加用户">
  </body>
</html>

2.后台代码

   public class UserAction extends ActionSupport {

   //属性定义,同时生成get,set方法,用于获取参数 username 和 password

   private String username;
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

   public String add() throws IOException{
        if(username != null){
            String msg="test ajax";
            
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(msg);
            out.flush();
            out.close();
        }
        System.out.println("username=" + username);//当点击按钮时,控制台可以看到打印的值,是ajax发过来的参数。
        System.out.println("password="+password);//
        System.out.println("test success");
        return "add_success";
    }

   }

3.代码解析

    (1)点击按钮

     (2)jQuery通过var $oDiv = $("#ajax");获取按钮这个对象-

      (3)给对象帮定点击事件 

       $oDiv.click(function(){

       $.ajax({
            type:"GET",//发送请求类型
            url:"user!add",//请求路径
            //async:false,//默认为true,是异步请求
            //传参给后台的形式(两种方式)
            //data:{"username":"test","password":"123456"},
            data:"username=test&password=123456",
            dataType:"script",//返回类型
            cache: false,//不使用当前浏览器的缓存
            success:function(msg){//请求成功后调用的回调函数
                //请求成功
                alert("msg="+msg);
                alert("success");
            },
            error:function(){
                //Exception
                alert("error");
            }
        });

   });

     (4)发送ajax请求后台,根据 url:"user!add",//请求路径找到后台的add方法

            该方法能获取前面传递的参数username 和password,同时创建我们要返回

           到前端异步请求的数据。

         public String add() throws IOException{
         if(username != null){

           //创建ajax请求交换的数据msg

            String msg="test ajax";
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(msg);
            out.flush();
            out.close();
        }
        System.out.println("username=" + username);
        System.out.println("password="+password);
        System.out.println("test success");
        return "add_success";
    }

   (5)前端回调函数直接就能拿到后台设定的值,通过alert(msg)就能得到后台设定的String msg = "test ajax".

    success:function(msg){//请求成功后调用的回调函数
                //请求成功
                alert("msg="+msg);
                alert("success");
            },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值