• 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);
    }
    
  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/fanbi/p/7705352.html
Copyright © 2020-2023  润新知