ajax - json - controller

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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,073评论 19 139
  • 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 11. Developing ...
    SnailTyan阅读 4,858评论 0 3
  • 原文链接:http://www.dropwizard.io/1.2.0/docs/getting-started....
    Lance_Xu阅读 4,661评论 0 0
  • 横滨是我来东京去了之后还想去的城市,美如画的风景,干净的白色建筑,蓝色海风,一切都是初夏的感觉,空气中弥漫着浪漫的...
    雁儿与安阅读 2,865评论 1 1
  • 今早委托25,太贪心结果没成,最后20成交,直接上图: 第一次委托如下图: 最终成交记录如下图: 收益预估:净收益...
    Adamwyg阅读 2,507评论 0 0

友情链接更多精彩内容