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