• ajax返回json对象的两种写法


    1. 前言

    dataType: 要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。

      response.setContentType("text/html"); //一般默认返回的类型自己指定(有xmlDoc、jsonObj、html、text这几种)

    如果返回字符串是json的字符串,希望返回的数据为json对象,可以在返回时设置

       response.setContentType("text/json");

    或者

      让其返回json字符串然后再转成json对象(见http://www.cnblogs.com/fanbi/p/7289551.html)。

    2.方法

    第一种

    JS代码:

    $.ajax({
    		type: 'POST',
    		data : { 
    			   mode:"getData", 
    			   id:id,
    			 },
    		url : './data',
    		dataType: 'json', //添加这一条语句	
    		success: function(msg) {
    		if(msg.status == "success"){
    	 	    	//todo sth			
    	 					
    	 	    }
    		}                              
    	});  

    Java代码:

    String status = "{"status":"success"}";
    	
    //response.setContentType("text/json");
    IOUtils.write(status.getBytes(), response.getOutputStream());
    //或者
    try (PrintWriter writer = response.getWriter();) {
        writer.write(status);
        writer.flush();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    
    

    第二种

    JS代码:

    $.ajax({
    		type: 'POST',
    		data : { 
    			   mode:"getData", 
    			   id:id,
    			 },
    		url : './data',
    		success: function(msg) {
    		if(msg.status == "success"){
    	 	    	//todo sth			
    	 					
    	 	    }
    		}                              
    	});  

    Java代码:

    String status = "{"status":"success"}";
    	
    response.setContentType("text/json");
    IOUtils.write(status.getBytes(), response.getOutputStream()); 
    //或者
    try (PrintWriter writer = response.getWriter();) {
        writer.write(status);
        writer.flush();
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
    
  • 相关阅读:
    C阶段【01】
    Xcode常用快捷键的使用
    eclipse中添加web app libraries
    hibernate 连接SQL SERVER2008
    hibernate配置入门(个人总结)
    项目编译PNG报错
    项目archive打包编译报错
    项目上传
    Git本地项目上传,版本管理工具与GitHub的简单结合使用
    将制定目录下的内容复制到另一个路径下
  • 原文地址:https://www.cnblogs.com/fanbi/p/7705352.html
Copyright © 2020-2023  润新知