SpringMVC 4.2 Ajax实现

今天带给大家的SpringMVC Ajax的一个demo,那么先把配置文件servlet-context.xml文件贴出来

1.解决配置问题

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven >
	</annotation-driven>

	<resources location="/resources/" mapping="/resources/**"></resources>
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/resources/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="com.hongjian.controller" />
	
	
	
</beans:beans>
将实体类entity转换为json的Json2Converter在写出<annotation-driven/>之后,就已经默认地加上,基本上不用配置什么东西。你的@RequestBody和@ResponseBody注解就可以使用啦

2.在pom.xml中加入相应的json包,这里如果你使用的是spring 4.x的新版本,则导入的是jackson的2.x的jar包,如下

<!-- json -->
        <dependency>
	        <groupId>com.fasterxml.jackson.core</groupId>
	        <artifactId>jackson-core</artifactId>
	        <version>2.4.3</version>
   		 </dependency>
	    <dependency>
	        <groupId>com.fasterxml.jackson.core</groupId>
	        <artifactId>jackson-databind</artifactId>
	        <version>2.4.3</version>
	    </dependency>
3.编写发起Ajax异步请求的页面

html>
	<head>
		<title>表单从后台获取数据</title>
		<link rel="stylesheet" type="text/css" href="/newtry/resources/css/obaMeMeDa.css"/>
		<script type="text/javascript" src="/newtry/resources/scripts/jquery.js"></script>
	 	<script type="text/javascript" src="/newtry/resources/scripts/obaMeMeDa.js"></script>
	 	<script type="text/javascript" src="/newtry/resources/scripts/json2.js"></script>
	</head>
	<body>
		<h1>用户注册界面</h1>
		<form id="formSign"  action="" method="post" >
			<div class="inputName">
				<label for="userName">姓名:</label>
				<input type="text" id="userName" name="name" />
			</div>
			<div class="checkSex">
				<label for="sex">性别:</label>
				<input type="radio" id="sex" class="sex" name="sex" value="male" />男
				<input type="radio" id="sex" class="sex" name="sex" value="female" />女
				<input type="radio" id="sex" class="sex" name="sex" value="otherSex" />其他
			</div>
			<div class="userAge">
				<label for="userAge">年龄:</label>
				<input type="text" id="userAge" name="age"/>
			</div>
			<div class="button">
				<input type="reset" class="reset1" value="重置">
				<input type="submit" class="submit1" value="提交" />
			</div>

		</form>


	</body>
</html>
4.上面的json2.js和jQuery.js的库自己使用src导入当前页面,接下来是实现Ajax的自己编写的js

$(

	function postData(){
		console.log("进入");
		/*var userName =$("#userName").val();
		var sex =$("input.sex[type='radio']:checked").val();
		var userAge = $("userAge").val();*/
        //注意该变量需放置在函数在开始。
        //同时!注意!获取“被选择单选框”“值”的“写法”!!“:checked”

        //将表单中的内容,直接序列化为字符串。


        function addMessage(jsonToObjData){
        	var responseName = jsonToObjData.name;
        	var responseSex = jsonToObjData.sex;
        	var responseAge = jsonToObjData.age;

        	$("body").append('<p>欢迎'+responseName+'+'+responseSex+'士'+',您已注册成功!'+'您的年龄是:'+responseAge+'岁。</p>')
        }
		$(".submit1").click(
			function postJson(event){
				event.preventDefault();
//第一种				
//		        var formContent = $("#formSign").serialize();
//				console.log("表格内容序列化结束");
//				console.log(formContent);
//第二种测试,原生JS可以使用
// 			var userName = document.getElementById("userName").value;
//				var userSex = document.getElementById("sex").value;
//				var userAge = document.getElementById("userAge").value;
//				console.log(userName);
//				console.log(userSex);
//				console.log(userAge);
//				var formContent = {'name':userName,'sex':userSex,'age':userAge};
//				console.log(formContent);
//				$("body").append(formContent)
//第三种,纯测试,可以使用
//				var formContent = {'name':'洪坚','sex':'男','age':'21'};
//第四种,jQuery对象获取值,加#获取jQuery对象后,使用期.val()方法获取输入值 
//可以使用				
	 			var userName = $("#userName").val();
				var userSex = $("#sex").val();
				var userAge = $("#userAge").val();
				console.log(userName);
				console.log(userSex);
				console.log(userAge);
				var formContent = {'name':userName,'sex':userSex,'age':userAge};
				console.log(formContent);
				$.ajax(
				{
					
					contentType : "application/json",
					url: "jsonTest",//写有json数据的地址
					
					type:"POST",
					dataType:"json",   //服务器返回的数据类型
//					data:JSON.stringify(formContent[0]),//发送过去的json数据
//					data:formContent,//发送过去的json数据
					data:JSON.stringify(formContent),//发送过去的json数据
						 
					success:function(data){ //其中的data为从服务器返回的json数据
						//javascript已自动将返回的json数据转为对象了
						addMessage(data);
						console.log("表格成功发送数据");
						
					}, 
					error : function() {
						console.log("数据传输不成功");
					},
					complete:function(XMLHttpRequest,textStatus){
						console.log(textStatus);
					}
				}
				);
			}
		)
	}
)
event.preventDefault()方法是阻止表单数据的默认提交行为即新窗口打开,那么自然也就不会发送数据到<form>中的action对应的地址。

这里还容易出问题的地方有:如果是传Json字符串,则加上ContentType=“appLication/json”,传文本的话里面自然是"text",dataType指的是接收返回数据类型。这里要注意,url那个地方,如果运行提示找不到。。这样类似的错误,请加上/项目名。


5.处理json数据的Controller

@Controller
public class JsonTestController {
	
	@RequestMapping(value="/jsonTest",method=RequestMethod.POST)
	public@ResponseBody User JsonTest(@RequestBody User user){
		System.out.println(user.getName());
		System.out.println(user.getSex());
		System.out.println(user.getAge());
		user.setName("ItIsWhat");
		user.setSex("youguess");
		user.setAge("21");
		return user;
	}
	
	
	
}

写到这里基本也就完成了ajax的传输交互过程


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值