ajax实例

Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。

Ajax = 异步 JavaScript 和 XML标准通用标记语言的子集)。
Ajax 是一种用于创建快速动态网页的技术。
Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
 
下面举个例子以便理解,对$.ajax不太熟悉的可以参照我的上篇博客http://www.cnblogs.com/lwx521/p/7993332.html
前台
<script src="js/jquery-1.10.2.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {     
    $("#name").blur(function () {
        $.ajax({
            type:"post",
            url:"lll",
            data:{"name":$("#name").val()},
            async:false,
            success:function(msg){
                if(msg=="N"){alert("用户不存在!")}
            },
            error:function(){
                alert(error);
            }
        })    
    })
    
})
</script>

<form class="form-horizontal" role="form" id="vForm" method="POST" action="list">
<div class="form-group ">
<label for="name" class="col-sm-4 control-label">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
</div>
<div class="form-group">
<label for="passowrd" class="col-sm-4 control-label">密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
</div>
</div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3 control-label ">
<button type="button" class="btn btn-info" id="bu">登录</button>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="register" class="btn btn-info">注册</a>
</div>
</div>
</form>

后台

@RequestMapping("/lll")
      public String testlll(String name,HttpServletResponse response) {
         System.out.println(name);
String msg = "N"; if(name.equals("user"){
msg = "Y"
}
try { PrintWriter out=response.getWriter(); out.write(msg); out.flush();//这句千万不能少 } catch (IOException e) { e.printStackTrace(); } return msg; }

功能很简单就是比较输入框的数据和后台数据是否相同,延伸一下实现的功能就很多了,比如登录验证,注册验证等

原文地址:https://www.cnblogs.com/lwx521/p/7994268.html