jquery ajax 使用demo
1)pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xiaoma</groupId>
<artifactId>zjl</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>zjl Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.23</version>
</dependency>
</dependencies>
<build>
<finalName>zjl</finalName>
</build>
</project>
2)controller
package com.mymyajax.controller;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.myajax.entity.User;
import com.myajax.utils.JSONUtils;
@Controller
@RequestMapping("/testController")
public class LoginController {
@RequestMapping(value = "test0.do")
public String test0(HttpServletRequest request, HttpServletResponse response)
throws IOException {
return "index";
}
@RequestMapping(value = "test1.do")
public @ResponseBody String test1(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
User user = new User();
user.setName(name);
user.setAge(age);
return JSONUtils.c(user);
}
@RequestMapping(value = "test2.do")
public @ResponseBody Map<String, Object> test2(User user,
HttpServletResponse response) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", user.getName());
map.put("age", user.getAge());
return map;
}
@RequestMapping(value = "test3.do")
public @ResponseBody String test3(@RequestBody User user,
HttpServletResponse response) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", user.getName());
map.put("age", user.getAge());
return JSONUtils.c(user);
}
@RequestMapping(value = "test4.do")
@ResponseBody
public String test4(@RequestBody User[] users) {
return JSONUtils.c(users);
}
@RequestMapping(value = "test5.do")
public @ResponseBody String test5(HttpServletRequest request,
@RequestParam String name, @RequestParam String age,
HttpServletResponse response) throws IOException {
User user = new User();
user.setName(name);
user.setAge(age);
return JSONUtils.c(user);
}
@ResponseBody
@RequestMapping("test6.do")
public String test6(
@RequestParam(value = "file", required = false) MultipartFile file,
String name, String age, HttpServletRequest request) { // name和addrinfo是表单提交的数据
String fileName = file.getOriginalFilename(); // 获取文件名
if (!file.isEmpty()) {
String path = "";// 写你的路径 这里不写了
File targetFile1 = new File(path, fileName);
}
User user = new User();
user.setAge(age);
user.setName(fileName);
return JSONUtils.c(user);
}
}
3)工具类
package com.myajax.utils;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
* @cf
*/
public class JSONUtils {
/**
* @param o
* @param prettyFormat
* @return
*/
public static String c(Object o) {
return JSON.toJSONString(o);
}
/**
* @param o
* @param prettyFormat
* @return
*/
public static String c(Object o, SerializerFeature... features) {
return JSON.toJSONString(o, features);
}
/**
* @param json
* @param clazz
* @return
*/
public static <T> T p(String json, Class<T> clazz) {
if (json == null || clazz == null) {
return null;
}
return JSON.parseObject(json, clazz);
}
/**
* @param json
* @param clazz
* @return
*/
public static <E> List<E> pa(String json, Class<E> clazz) {
if (json == null || clazz == null) {
return null;
}
return JSON.parseArray(json, clazz);
}
/**
* @param json
* @param clazz
* @return
*/
public static <T> T t(Object o, Class<T> clazz) {
return p(c(o), clazz);
}
}
4)实体
package com.myajax.entity;
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
5)spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射 -->
<mvc:annotation-driven />
<!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="com.mymyajax.controller" />
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/" p:suffix=".jsp" />
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 与 jquery ajax formdata 配合使用-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过1024*1024*10=10MB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="-1" />
<!--被允许的最大的内存的大小,Default is 10240 bytes -->
<property name="maxInMemorySize" value="10240" />
</bean>
</beans>
6)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 应用上下文配置文件 -->
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置spring核心servlet -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- url-pattern配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问。如配为*.do,则不影响静态文件的访问 -->
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
7)index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<html>
<meta charset="utf-8">
<script type="text/javascript" src="${ctx}/js/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("input[type='button']").bind("click", function() {
$.ajax({
type : 'get',
url : '${ctx}/testController/test1.do',
dataType : 'json',
data : $('#f1').serialize(),
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
},
error : function(xmlq, errq) {
alert(errq);
}
});
});
});
function ajaxPost1() {
var jsonData = {
"name" : "cf",
"age" : "23"
}
$.ajax({
url : "${ctx}/testController/test1.do",
type : "get",
data : jsonData,
dataType : "json",
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
}
});
}
function ajaxPost2() {
var jsonData = {
"name" : "雨轩",
"age" : "23"
}
$.ajax({
url : "${ctx}/testController/test2.do",
type : "POST",
data : jsonData,
dataType : "json",
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
}
});
}
function ajaxPost3() {
var jsonData = {
"name" : "雨轩",
"age" : "23"
}
$.ajax({
url : "${ctx}/testController/test3.do",
type : "POST",
data : JSON.stringify(jsonData),
contentType : 'application/json',
dataType : "json",
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
}
});
}
function ajaxPost3_1() {
var jsonData = {
"name" : "雨轩",
"age" : "23"
}
$.ajax({
url : "${ctx}/testController/test2.do",
type : "POST",
data : JSON.stringify(jsonData),
contentType : 'application/json',
dataType : "json",
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
}
});
}
function ajaxPost4() {
var saveDataAry = [];
var data1 = {
"name" : "雨轩",
"age" : "36"
};
var data2 = {
"name" : "福尔摩斯",
"age" : "47"
};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
type : "POST",
url : "${ctx}/testController/test4.do",
dataType : "json",
contentType : "application/json",
data : JSON.stringify(saveDataAry),
success : function(data) {
alert(data);
}
});
}
function ajaxPost5() {
$.ajax({
url : '${ctx}/testController/test5.do',
type : 'POST',
cache : false,
data : new FormData($('#f2')[0]),
processData : false, //必须false才会避开jQuery对 formdata 的默认处理
contentType : false, //必须false才会自动加上正确的Content-Type
success : function(data) {
alert(data);
}
});
}
function ajaxPost6() {
$.ajax({
url : '${ctx}/testController/test6.do',
type : 'POST',
cache : false,
data : new FormData($('#f3')[0]),
processData : false, //必须false才会避开jQuery对 formdata 的默认处理
contentType : false, //必须false才会自动加上正确的Content-Type
success : function(xmlq) {
alert("姓名:" + xmlq.name + " 年龄:" + xmlq.age);
}
});
}
</script>
<h2>Jquery ajax使用详解!</h2>
<button onClick="ajaxPost1()">点击提交1</button>
<button onClick="ajaxPost2()">点击提交2</button>
<button onClick="ajaxPost3()">点击提交3</button>
<button onClick="ajaxPost3_1()">点击提交3.1</button>
<button onClick="ajaxPost4()">点击提交4</button>
<form name="f1" id="f1" action="${ctx}/testController/test1.do">
用户名:<input type="text" name="name1" /> 年龄:<input type="text"
name="age1" /> <input type="button" value="Ajax请求" />
</form>
<form name="f2" id="f2" action="${ctx}/testController/test5.do">
用户名:<input type="text" name="name" /> 年龄:<input type="text" name="age" />
<input type="button" value="formData" onClick="ajaxPost5()" />
</form>
<form name="f3" id="f3" action="${ctx}/testController/test6.do">
用户名:<input type="text" name="name" /> 年龄:<input type="text" name="age" />
<input type="file" name="file" /> <input type="button"
value="formData" onClick="ajaxPost6()" />
</form>
</html>
备注:
1、@RequestBody需要把所有请求参数作为json解析,因此,不能包含key=value这样的写法在请求url中,所有的请求参数都是一个json
2、直接通过浏览器输入url时,@RequestBody获取不到json对象,需要用java编程或者基于ajax的方法请求,将Content-Type设置为application/json
JSON.stringify() : 将对象转换成json字符串。
JSON.parse(): 将json字符串转换成json对象。
Java:
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody List<User> users) {
userService.batchSave(users);
}
这样是不可以的。因为spring MVC不会自动转换为List<User>对象。传到后台后,List中是LinkedHashMap类型。
但是使用数组就可以接受了User[] ,如下:
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }})
@ResponseBody
public void saveUser(@RequestBody User[] users) {
userService.batchSave(users);
}