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);
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM