ajax(cors跨域)最简单输出json数据方法,无需第三方框架或代码

/**
	 * cors输出json数据
	 * @param response
	 * @param json json字符串
	 * @param domain 需要跨域的域名
	 */
	protected void outputCrossString(final HttpServletResponse response, final String json, final String domain) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Access-Control-Allow-Origin", domain); //核心请求头
			response.setHeader("Access-Control-Allow-Credentials", "true"); //核心请求头
			PrintWriter out = null;
			try {
				out = response.getWriter();
				out.write(json);
				out.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
输出json数据只需调用这个方法即可

你可能感兴趣的:(前端技术)