2.ajax+springmvc+json

1、表单验证/字典/往url传值

<input type="text" id="txt1" οnkeyup="showHint(this.value)" />

<span id="txtHint"></span>

     xmlhttp.open("GET","/ajax/gethint.asp?q="+str,true);

    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

http://www.w3school.com.cn/tiy/t.asp?f=ajax_suggest


2、ajax+springmvc+json  前端接收mvc传递来的json数据

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
        <title>ajax for springMVC</title> 
        <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script> 
        <script type="text/javascript"> 
            $(function() { 
                $("#click").click(function() { 
                    $.ajax( { 
                        type : "GET", 
                        url : "ajax.do", 
                        data : "name=zhangsan&age=20", 
                        dataType: "text", 
                        success : function(msg) { 
                       //jquery解析json
                        var obj = $.parseJSON(msg)  
                        alert(obj.name);  
                        alert(obj.age); 
                        $("#show").val(msg);
                        } 
                    }); 
                }); 
            }); 
        </script> 
    </head> 
    <body> 
        <input id="click" type="button" value="click to show person" /> 
        <input id="show" /> 
    </body> 
</html>

       
    @RequestMapping(value = "ajax.do", method = RequestMethod.GET) 
    public void ajax(@ModelAttribute Person person,PrintWriter printWriter) { 
        String jsonString = JSON.toJSONString(person, SerializerFeature.PrettyFormat); 
        printWriter.write(jsonString); 
        printWriter.flush(); 
        printWriter.close(); 
    } 


项目地址:http://download.csdn.net/detail/nickfover/8249075



3、ajax+springmvc+json ajax向springmvc传递json

<%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
<script type="text/javascript">  
  
    $(document).ready(function(){  
        //传递字符串格式json对象到后台(一个json对象)  
        $("#resolveJsonObject").click(function(){  
            var userName =encodeURI($("#userName").attr("value"));  
            var age = encodeURI($("#age").attr("value"));  
              //向mvc传递json对象
            var user = {userName:userName,age:age};  
            var aMenu  = encodeURI(JSON.stringify(user));  
  
            $.ajax({  
                 url:"resolveJsonObject" ,  
                 data:"orderJson=" + aMenu,    
                 success:function(data){  
                      
                }  
            });  
        });  
          
        //传递json数组到后台  
        $("#resolveJsonArray").click(function(){  
            var userName =encodeURI($("#userName").attr("value"));  
            var age = encodeURI($("#age").attr("value"));  
              
            //数组开始  
            var user1 = {userName:userName,age:age};  
            var allMenu={  
                "menu":[ ]  
                };  
            allMenu.menu.push(user1);   
            var allMenu1 = encodeURI(JSON.stringify(allMenu));  
              
            $.ajax({  
                //json数组  
                 url:"resolveJsonArray" ,  
                data:"orderJson=" + allMenu1,   
                success:function(data){  
                      
                }  
            });  
        });  
          
        //接收后台的json在前台解析  
        $("#resolveJson").click(function(){  
              
        	 $.ajax({  
                 //解析从后台返回的json数据  
                 url:"resolveJson" ,  
                 type:"post",          
                 success:function(data){  
                	 var arr=eval(data); 
                     for(var m = 0;m<arr.length;m++){  
                         alert(arr[m].user.userName);  
                     }  
                 }  
             });  
        });  
    });  
  
</script>  
</head>  
<body>  
    <h1>json添加用户</h1>   
      
    姓名:<input id="userName" type="text" name="userName">  
    年龄:<input id="age" type="text" name="age"><br>  
    <input type="button" id="resolveJsonObject" value="json对象">  
    <input type="button" id="resolveJsonArray" value="json数组">  
    <input type="button" id="resolveJson" value="前端解析json字符串">  
    
</body>  
</html>  


package org.nick.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.nick.demo.Person;
import org.nick.demo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;


@Controller
public class BaseController {
	@RequestMapping("/link")
	public String fun3(){
		return "/link";
	}
	 @RequestMapping("toAjax.do") 
	    public String toAjax() { 
	        return "ajax"; 
	    } 
	       
    @RequestMapping(value = "ajax.do", method = RequestMethod.GET) 
    public void ajax(@ModelAttribute Person person,PrintWriter printWriter) { 
        String jsonString = JSON.toJSONString(person, SerializerFeature.PrettyFormat); 
        printWriter.write(jsonString); 
        printWriter.flush(); 
        printWriter.close(); 
    } 
    //接收前台传过来的字符串格式的json对象,在后台进行解析  
    @RequestMapping("/resolveJsonObject"    )  
    public void resolveJsonObject(HttpServletRequest request,HttpServletResponse response) throws IOException {  
        //解码  
        String str = URLDecoder.decode(request.getParameter("orderJson"),"UTF-8");  
        JSONObject jb=new JSONObject();   
        //将json格式的字符串转换为json对象,并取得该对象的“userName”属性值  
        String o=(String)jb.fromObject(str).get("userName");  
        System.out.println(o);  
    }   
      
     //传递json数组字符串  
    @RequestMapping("/resolveJsonArray" )  
    public void resolveJsonArray(HttpServletRequest request,HttpServletResponse response) throws IOException {  
        //解码,为了解决中文乱码  
        String str = URLDecoder.decode(request.getParameter("orderJson"),"UTF-8");  
        JSONObject jb=new JSONObject();  
        //将json格式的字符串转换为json数组对象  
        JSONArray array=(JSONArray)jb.fromObject(str).get("menu");  
        //取得json数组中的第一个对象  
        JSONObject o = (JSONObject) array.get(0);//获得第一个array结果  
        //取出json数组中第一个对象的“userName”属性值  
        String name=o.get("userName").toString();//获得属性值  
        System.out.println(name);  
    }   
      
    //通过该函数返回json格式的数据,在前台通过JQuery进行解析  
    @RequestMapping("/resolveJson"  )  
    public void resolveJson(HttpServletRequest request,HttpServletResponse response) throws IOException {  
          
        List m = (List) new  ArrayList();  
        JSONArray jsons = new JSONArray();  
        for(int i=0;i<10;i++){  
            User user = new User();  
            user.setUserName("name_" + i);  
            m.add(user);  
        }  
          
        for(int j=0;j<m.size();j++){  
            JSONObject jsonObject = new JSONObject();  
            jsonObject.put("user", m.get(j));  
            jsons.add(jsonObject);  
        }  
        //火狐浏览器要添加如下格式设置utf-8
        response.setContentType("text/html;charset=UTF-8");
        System.out.println(jsons.toString());
        response.getWriter().print(jsons.toString()) ;   
    }   
      
    @RequestMapping("/toJson"   )   
    public String toJson() {  
        return "/json";  
    }  
}  

http://localhost:8080/springmvc/link

项目下载:http://download.csdn.net/detail/nickfover/8251017


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值