废话不多说,请看代码和注释
代码语言:javascript复制<%--
Created by IntelliJ IDEA.
User: root
Date: 17-1-19
Time: 下午2:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Ajax类别</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {//serializeArray()
$.post("ajax/login2.do", $("#form1").serializeArray(),function (data, textStatus) {
$("#rs8").html(data.msg);
});
//阻止表单提交
return false;
});
});
function getString() {
$.ajax({
url: "ajax/getString.do",
dataType:"text",
data: {},
success: function(data) {
$("#rs1").html(data);
},
error:function (data){
$("#rs1").html("error");
}
});
}
function getStringByName() {
var name=$("#myname").val();
$.ajax({
url: "ajax/getStringByName.do",
dataType:"text",
data: {"name":name},
success: function(data) {
$("#rs2").html(data);
},
error:function (data){
$("#rs2").html("error");
}
});
}
function getJson() {
$.ajax({
url: "ajax/getJson.do",
dataType:"json",
data: {},
success: function(data) {
$("#rs3").html(data.msg);
},
error:function (data){
$("#rs3").html("error");
}
});
}
function byGet() {
//回调函数:data是返回的内容,可以是text/html/json类型
//textStatus是请求状态,包括success/error/notmodified/timeout4种,只有返回success才会调用回调函数
$.get("ajax/getString.do", function (data, textStatus) {//也可以认该回调函数是处理成功回调函数
$("#rs4").html(data);
}, "text");
}
function byGetJson() {
$.get("ajax/getJson.do", function (data, textStatus) {
$("#rs5").html(data.msg);
}, "json");
}
function byGetByName() {
$.get("ajax/getStringByName.do", {name:$("#name").val()},function (data, textStatus) {
$("#rs6").html(data);
}, "html");
}
function login() {
$.post("ajax/login.do", {
uname:$("#uname").val(),
upass:$("#upass").val()
},function (data, textStatus) {
$("#rs7").html(data.msg);
}, "json");
}
</script>
</head>
<body>
<h3>1. ajax()基本方式</h3>
<h4>(1) ajax()函数,无参数传递,返回普通字符串</h4>
<input type="button" οnclick="getString()" value="点我"/> -> <span id="rs1"></span><br>
<h4>(2) ajax()函数,有参数传递,返回普通字符串(有乱码)</h4>
请输入你的名字:<input type="text" id="myname" size="10"/><br>
<input type="button" οnclick="getStringByName()" value="点我"/> -> <span id="rs2"></span><br>
<h4>(3) ajax()函数,无参数传递,返回Json字符串(无乱码)</h4>
<input type="button" οnclick="getJson()" value="点我"/> -> <span id="rs3"></span><br>
<hr>
<h3>2. get方式:传输数据小于2K,有缓存,不安全</h3>
<h4>(4) get()函数,文本类型</h4>
<input type="button" οnclick="byGet()" value="点我"/> -> <span id="rs4"></span><br>
<h4>(5) get()函数,Json类型</h4>
<input type="button" οnclick="byGetJson()" value="点我"/> -> <span id="rs5"></span><br>
<h4>(6) get()函数,含参</h4>
请输入你的名字:<input type="text" id="name" size="10"/><br>
<input type="button" οnclick="byGetByName()" value="点我"/> -> <span id="rs6"></span><br>
<hr>
<h3>3. post()方式:安全,传输数据无限制</h3>
<h4>(7) post()函数,含参</h4>
帐号:<input type="text" id="uname" size="10"/><br>
口令:<input type="password" id="upass" size="10"/><br>
<input type="button" οnclick="login()" value="点我"/> -> <span id="rs7"></span><br>
<h4>(8) post()函数,表单</h4>
<h4>springMVC与Struts2的注入方式不同,直接写字段名</h4>
<form id="form1">
帐号:<input type="text" id="username" name="username" size="10"/><br>
口令:<input type="password" id="password" name="password" size="10"/><br>
<input type="submit" value="点我"/> -> <span id="rs8"></span><br>
</form>
<h4>$.post和$.get默认是采用异步的形式向服务器发送请求</h4>
</body>
</html>
代码语言:javascript复制package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
import bean.UserBean;
import org.springframework.web.multipart.MultipartFile;
import util.FileUtil;
/**
* Created by root on 17-1-19.
*/
@Controller
@RequestMapping("/ajax")
public class AjaxController {
/**
* 返回字符串
* @return
*/
@RequestMapping(value = "getString.do")
@ResponseBody
public String getString(){
return "Hell,world!";
}
/**
* 传递简单参数
* @param name
* @return
*/
@RequestMapping("getStringByName.do")
@ResponseBody
public String getStringByName(@RequestParam("name")String name){
return "Hello," name;
}
/**
* 返回Map
* @return
*/
@RequestMapping("getJson.do")
@ResponseBody
public Map<String, Object> getJson(){
Map<String, Object> map=new HashMap<String, Object>();
//将被解析为{"name":"Hello,中国!"}
map.put("msg","Hello,中国!");
return map;
}
/**
* 返回Map
* @return
*/
@RequestMapping("login.do")
@ResponseBody
public Map<String, Object> login(@RequestParam("uname")String uname,@RequestParam("upass")String upass){
Map<String, Object> map=new HashMap<>();
System.out.println(uname ":" upass);
map.put("msg",uname ":" upass);
return map;
}
/**
* 返回Map
* @return
*/
@RequestMapping("login2.do")
@ResponseBody
public Map<String, Object> login2(UserBean user){
Map<String, Object> map=new HashMap<>();
String msg=user.getUsername() ":" user.getPassword();
System.out.println(msg);
map.put("msg",msg);
return map;
}
}
代码语言:javascript复制package bean;
/**
* Created by root on 17-1-20.
*/
public class UserBean {
private String username;
private String password;
private String header;
@Override
public String toString() {
return "UserBean{"
"username='" username '''
", password='" password '''
", header='" header '''
'}';
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
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;
}
}
带参数的文件上传,使用了jquery.form.js插件
代码语言:javascript复制<%--
Created by IntelliJ IDEA.
User: root
Date: 17-1-20
Time: 下午1:20
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>带参数的文件上传</title>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(function () {
$("#form1").submit(function () {
//$(this).ajaxSubmit(options)
$(this).ajaxSubmit({
type: "POST",
url: "ajax/regist.do",
dataType: "json",
beforeSubmit: checkForm,//提交前数据校验
success: function(data){
$("#rs").html(data.msg);
}
});
return false;
});
});
//beforeSubmit回调函数带三个调用参数:数组形式的表单数据,jQuery表单对象,以及传入ajaxForm/ajaxSubmit中的Options对象
function checkForm(formData, jqForm, options) {
if(formData[0].value=="" || formData[0].value==null){
$("#rs").html("请输入帐号!");
return false;
}
if(formData[1].value=="" || formData[1].value==null){
$("#rs").html("请输入口令!");
return false;
}
var file= $("#file").val();
if (file == "") {
$("#rs").html("请选择头像图片!");
return false;
}
var suffix = file.substr(file.lastIndexOf('.') 1);
if (suffix!='jpg' && suffix != 'png') {
$("#rs").html("请选择jpg或者png格式的图片!");
return false;
}
}
</script>
</head>
<body>
<h3>输入信息</h3>
<form id="form1" enctype="multipart/form-data">
帐号:<input type="text" id="username" name="username" size="10"/><br>
口令:<input type="password" id="password" name="password" size="10"/></span><br>
头像:<input type="file" name="file" id="file"/><br>
<input type="submit" value="点我"/><br>
<span id="rs"></span>
</form>
</body>
</html>
后台处理程序
代码语言:javascript复制@RequestMapping(value = "regist.do",method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> regist(@RequestParam(value="file",required=false) MultipartFile file, UserBean user){
System.out.println("regist.do is start...");
String newname="/root/header/" System.currentTimeMillis() file.getOriginalFilename();
FileUtil.copy(file,newname);
Map<String, Object> map=new HashMap<>();
user.setHeader(newname);
System.out.println(user);
map.put("msg",user.toString());
return map;
}
代码语言:javascript复制package util;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
/**
* Created by root on 17-1-20.
*/
public class FileUtil {
public static boolean copy(MultipartFile file, String to){
if(!file.isEmpty()){
System.out.println("正在上传文件: " file.getOriginalFilename());
try {
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(to));
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}else{
System.out.println("空文件!");
return false;
}
}
}