Ajax的使用是很经常的,最近在写自己的博客系统的时候也用到了,在这总结一下用法,有完整例子
本文章统一用index.jsp页面
<div id="info"></div>
<form action="add" method="post" id="form">
姓名:<input type="text" name="username" />
年龄:<input type="text" name="age" />
<input type="button" value="提交" id="submit" />
</form>
form表单参数转换
主要是json交互需要使用
-
序列化成拼接字符串(用serialize())
$('#form').serialize() //
结果:
- 转换成json对象
先将form表单参数转换成对象
//将一个表单的数据返回成对象
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null && this.value != '') {
value = this.value;
} else {
value = null;
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [ objectData[this.name] ];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
}
再用JSON.stringify()方法转化为json对象即可
var Object = $('#form').serializeObject();
var json = JSON.stringify(Object);
注意:
- stringify()用于从一个对象解析出字符串
var str = {a:1,b:2};
JSON.stringify(str);
结果:
"{"a":1,"b":2}"
parse()用于从一个字符串中解析出json对象
var str = '{"name":"hope","age":"20"}';
JSON.parse(str);
结果:
Object
age: "23"
name: "hope"
__proto__: Object
SpringMVC与ajax
- 环境:tomcat7.0, eclipse, jdk1.8
Spring4.3.4, jackson2.8.7 - 添加SpringMVC支持json的jar包下载地址,或者去Maven仓库下载
如图:
注意: 如果运行出现java.lang.NoSuchMethodError: com.fasterxml
异常,说明Spring版本与json版本不兼容,解决方案:提高json版本。
-
新建index.jsp(在文章开头)
- 新建模型
UserModel
package com.entity;
public class UserModel {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
- 新建UserController
package com.controller;
import java.util.*;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.annotations.common.util.impl.LoggerFactory;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.entity.UserModel;
@Controller
@RequestMapping("/user")
public class UserController {
private org.jboss.logging.Logger logger = LoggerFactory.logger(UserController.class);
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody //必须要有
public Map<String, Object> getUserList() {
logger.info("获取列表成功");
List<UserModel> list = new ArrayList<UserModel>();
UserModel um = new UserModel();
um.setUsername("hope");
um.setAge(20);
list.add(um);
Map<String, Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", "1");
modelMap.put("data", list);
modelMap.put("success", "true");
return modelMap;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody //必须要有
public Map<String, String> addUser(@RequestBody UserModel model) {
logger.info("新增model");
logger.info("捕获到前台Model:" + model.getUsername());
Map<String, String> map = new HashMap<String, String>(1);
map.put("success", "true");
return map;
}
}
- 编写Ajax
<script>
//将一个表单的数据返回成对象
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null && this.value != '') {
value = this.value;
} else {
value = null;
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [ objectData[this.name] ];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
}
$(document).ready(
function() {
jQuery.ajax( {
type : 'GET',
contentType : 'application/json',
url : 'user/list',
dataType : 'json',
success : function(data) {
if (data && data.success == "true") {
$('#info').html("共" + data.total + "条数据。<br/>");
$.each(data.data, function(i, item) {
$('#info').append(
"姓名:" + item.username
+ ",年龄:" + item.age);
});
}
},
error : function() {
alert("error")
}
});
$("#submit").click(function() {
var Object = $('#form').serializeObject();
var json = JSON.stringify(Object);
jQuery.ajax( {
type : 'POST',
contentType : 'application/json',
url : 'user/add',
data : json,
dataType : 'json',
success : function(data) {
alert("新增成功!");
},
error : function(data) {
alert("error")
}
});
});
});
</script>
热门评论
兄弟,赞一个,正好我最近搞个'个人网站'。之前一直看Java, SpringMVC接收&返回值啥的都OK。现在, 遇到个问题:
怎么既跳转页面又能拿到数据呢(比如我跳转到个人详情页,又能拿到个人信息, SpringMVC只返回JSON)? ?
ajax怎么把该放的值放哪??