如何使用springmvc实现ajax的json格式的数据传输?

jsp页面 form表单中

 <div>
                    <label for="userCode">用户编码:</label>
                    <input type="text" name="userCode" id="userCode" value=""> 
					<!-- 放置提示信息 -->
					<font color="red"></font>
                </div>

js外置文件

/*
	 * 验证
	 * 失焦\获焦
	 * jquery的方法传递
	 */
	userCode.bind("blur",function(){
		//ajax后台验证--userCode是否已存在
		$.ajax({
			type:"GET",//请求类型
			url:path+"/user/ucexist.html",//请求的url
			data:{userCode:userCode.val()},//请求参数
			dataType:"json",//ajax接口(请求url)返回的数据类型
			success:function(data){//data:返回数据(json对象)
				if(data.userCode == "exist"){//账号已存在,错误提示
					validateTip(userCode.next(),{"color":"red"},imgNo+ " 该用户账号已存在",false);
				}else{//账号可用,正确提示
					validateTip(userCode.next(),{"color":"green"},imgYes+" 该账号可以使用",true);
				}
			},
			error:function(data){//当访问时候,404,500 等非200的错误状态码
				validateTip(userCode.next(),{"color":"red"},imgNo+" 您访问的页面不存在",false);
			}
		});
	}).bind("focus",function(){
		//显示友情提示
		validateTip(userCode.next(),{"color":"#666666"},"* 用户编码是您登录系统的账号",false);
	}).focus();

control层

         @RequestMapping(value="/ucexist.html")
	 @ResponseBody
	 public Object userCodeExit(@RequestParam String userCode){
		 HashMap<String,String> resultMap=new HashMap<String,String>();
		 if(StringUtils.isEmpty(userCode)){//空字符,什么都不输入的话//import org.apache.commons.lang.StringUtils;
			 resultMap.put("userCode", "exist");
		 }else{
			 User user=userService.selectUserCodeExist(userCode);
			 if(null!=user){//查询数据库存在该usercode
				 resultMap.put("userCode", "exist"); 
			 }else{
				 resultMap.put("userCode", "noexist"); 
			 }
			 
		 }
		 System.out.println(JSONArray.toJSONString(resultMap));
		return JSONArray.toJSONString(resultMap);
	 }

补充:若是json格式的对象进行数据传输,遇到日期需要格式化,不然会出现乱码

springmvc文件中先配置

            <mvc:annotation-driven>
               <mvc:message-converters>
               		<bean class="org.springframework.http.converter.StringHttpMessageConverter">
               		          <property name="supportedMediaTypes">
               		          		<list>
               		          			<value>application/json;charset=UTF-8</value>
               		          			
               		          		</list>
               		          </property>
               		</bean>
               </mvc:message-converters>
          </mvc:annotation-driven>

pojo对应的实体类属性上需要注解

 @JSONField(format="yyyy-MM-dd")
private Date birthday;  //出生日期

猜你喜欢

转载自blog.csdn.net/java_stud/article/details/81047481