Ajax与SpringMVC交互详解

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>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值