SpringMVC的Ajax用法一与平时的Ajax用法是一样的。只是请求是交给对应的Controller。
jQuery知识
$(“#username”).val();//jQuery取对应元素的value
$(“#info”).text(“username正确”);//text()用来修改元素文本的值
$(“#info”).css({color: “green”});//css()用来为元素添加样式
$(“#username”).bind(‘input’,function(){});//绑定输入框的input事件,当输入时就会触发事件
实例:
index.jsp界面,主要是其中Ajax的运用
<%@ 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="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script src="js/jquery-1.8.1.js"></script>
<script>
$(function(){
//为输入框绑定input事件
$("#username").bind('input',function(){
//jQuery Ajax
$.ajax({
type:"POST",//post方式
url: "user/validate.do",//请求的地址
contentType:"application/x-www-form-urlencoded;charset=utf-8",//发送的data内容编码方式
dataType: "text",//返回的数据为文本
data:"username="+ $("#username").val(),//发送的data为输入框的信息
success: function(data){//返回的data
if(data=="true"){
//var msg = "username正确";
$("#info").text("username正确");
$("#info").css({color:"green"});
}
else{
$("#info").text("username不正确");
$("#info").css({color:"red"});
}
}
});
});
});
</script>
</head>
<body>
<p align="center">username:<input type="text" id="username" name="username"/></p>
<p align="center" id="info"></p>
</body>
</html>
控制器:ValidateServlet
package com.lin.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class ValidateServlet {
@RequestMapping("/validate.do")
public void validate(String username, HttpServletResponse resp) throws IOException{
System.out.println(username);//控制输出看ajax是否正常传输
PrintWriter out = resp.getWriter();//从response中获取输出流
if(username.equals("AAA")){
out.print(true);
}
else{
out.print(false);
}
out.flush();
out.close();
}
}