美文网首页
ajax - json - controller

ajax - json - controller

作者: ibyr | 来源:发表于2016-10-28 18:01 被阅读11次

First, you should have an ajax, like this:

// to send ajax request,and get response.
var collections_url = "http://localhost:8080/mysite/admin/collections";
// mysite is the project name. 
//   /admin is the @RequestMapping of the controller class. 
//   /collections is the @RequestMapping on handleCollections method.
var reqData = {collections: "true"};

$.ajax({    
    // attention: do not need to add contentType.
    type: "POST",    
    url: collections_url,    
    dataType: "json",    
    data: reqData,    
    success: function(dat){       //if ajax sends successfully, callback.
        console.log("return data: " + dat.myname); // ok        
        console.log("return data: " + dat.pass); // 12345       
        $.each(dat, function(index, value){            
            var na = dat[index].name;  //undefined            
            console.log("ajax success. item value: " + value);  // json value            
         });    
    },    
    error: function(err){        //if ajax failed, callback.
        console.log("return error for collections: " + err);   
    }
});

Then, you need a controller.

@RequestMapping(value="/collections", method=RequestMethod.POST)
public void handleCollections(HttpServletRequest request, HttpServletResponse response)        throws Exception{    
    String collections = request.getParameter("collections");    
    
    logger.debug("collections: " + collections);    //log4j
    response.setContentType("application/json;charset=utf-8");  // not necessary.  
    response.setCharacterEncoding("UTF-8");    

    PrintWriter out = null;    
    out = response.getWriter();   
    if(collections.equals("true")){  
        // First way to respopnse. To use JSON class.      
        JSONObject jsonObj = new JSONObject();        
        jsonObj.put("myname", "hhhhhhhhh");       
        jsonObj.put("pass", 12345);        
        out.write(jsonObj.toString());        

        // Another way to response.
        // If you use map, you should add an util method 
        // to convert map (java object) to json string. 
        // This method will be given below.
       /*Map<String, Object> map = new HashMap<String, Object>();        
        map.put("name", "hhhhh");  
        map.put("pass", 12345);      
        String json = Utils.toJson(map);        
        out.write(json);*/        

        out.flush();    
    }   
         out.close();
}
// If you use Map to give response to ajax.
public class Utils {    
    private static Gson gson = new Gson();    
    public static String toJson(Object obj){        
        if(obj == null)            
            return gson.toJson(JsonNull.INSTANCE);       
        return gson.toJson(obj);    
    }
}
/**
  * Note:
  * JsonNull.INSTANCE.toString().equals("null")  // true.
  */ 

So, you see, you'll use Gson or JSON.
Add jar in pom.xml, or you can add jars in lib directory.

// pom.xml (maven config file.)
<dependency>    
    <groupId>com.google.code.gson</groupId>    
    <artifactId>gson</artifactId>    
    <version> ${gson.version} </version>
</dependency>

<dependency>    
    <groupId> org.json </groupId>    
    <artifactId> json </artifactId>    
    <version> RELEASE </version>
</dependency>

<properties>
    <gson.version> 2.6.2 </gson.version>
</properties>

相关文章

网友评论

      本文标题:ajax - json - controller

      本文链接:https://www.haomeiwen.com/subject/wjeeuttx.html