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

前端之家收集整理的这篇文章主要介绍了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数据只需调用这个方法即可

猜你在找的Ajax相关文章