1. 程式人生 > >Ajax常見用法

Ajax常見用法

本人常用的ajax呼叫根據返回值區分主要有string型別和json兩種,現總結如下:

1.返回的是json字串

js寫法如下:

function getInstitutionStatus() {
	var name="永高駕校";
	var flag_id="22";
	$.ajax( {
		type : "post",
		url : basePath + "/dtsp/school/getInstitutionStatus.do?",
		data : {
			"flagId" : flag_id,
			"institutionName" : name
		},
		dataType : "json",
		success : function(data) {
			var checkStatus =data.checkStatus;
			alert(checkStatus);
		}
	});
}

 java程式碼寫法如下:

@RequestMapping({"/dtsp/school/getInstitutionStatus.do"})
    public String getInstitutionStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String checkStatus = "";
        try {
            String id = request.getParameter("flag_id");//通過此方法獲取js傳過來的值
            DtspInstitution dtspInstitution = institutionService.findInstitutionById(Long.valueOf(id));
            if (dtspInstitution != null) {
                checkStatus = dtspInstitution.getCheckStatus();
            }
            map.put("checkStatus", checkStatus);
            responseOutputJson(map, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void responseOutputJson(Map<String, Object> map, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache");//沒有快取
		response.setHeader("Pragma", "no-cache");//沒有快取
		response.setDateHeader("Expires", 0);//設定過期的時間期限
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		response.addHeader("charset", "charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String json = JSONObject.fromObject(map).toString();
			out.write(json);
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

 

2.返回的是string字串

js寫法如下(主要的區別是dataType的型別和得到的data轉成返回值的方法不一樣):

function getInstitutionStatus() {
	var name="永高駕校";
	var flag_id="22";
	$.ajax( {
		type : "post",
		url : basePath + "/dtsp/school/getInstitutionStatus.do?",
		data : {
			"flagId" : flag_id,
			"institutionName" : name
		},
		dataType : "text",
		success : function(data) {
			var array = data.split(",");
			var checkStatus =array[0];
			var status =array[1];
			alert(checkStatus);
		}
	});
}

java程式碼寫法如下(和json的區別主要是返回值的處理不同):

 @RequestMapping({"/dtsp/school/getInstitutionStatus.do"})
    public String getInstitutionStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	 StringBuilder result = new StringBuilder();
        String checkStatus = "";
        String status = "";
        try {
            String id = request.getParameter("flag_id");//通過此方法獲取js傳過來的值
            DtspInstitution dtspInstitution = institutionService.findInstitutionById(Long.valueOf(id));
            if (dtspInstitution != null) {
                checkStatus = dtspInstitution.getCheckStatus();
                status = dtspInstitution.getStatus();
            }
            result.append(checkStatus).append(",").append(status);
            responseOutputString(result.toString(), response);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public void responseOutputString(String result, HttpServletResponse response) {
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		response.addHeader("charset", "charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.write(result);
			response.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.flush();
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}