JSON—接收服务器端传来的数据

1.服务器端传送json格式的数据代码如下(这里指在servlet类中的情况):

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class repjson extends HttpServlet {
	public repjson() {
		super();
	}
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
        //主方法,通过doGet的response回传json数据
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String title="HelloJson";
		String a="J";
		String b="S";
		String c="O";
		String d="N";
		String xData="["+"\""+a+"\""+","+"\""+b+"\""+","+"\""+c+"\""+","+"\""+d+"\""+"]";
		String yData="["+4+","+3+","+2+","+1+"]";
		out.println("{" + "\"title\": \"" + title + "\"" + ","+ "\"xData\":" + xData + "," + "\"yData\":" + yData + "}");
	}

	public void init() throws ServletException {
		// Put your code here
	}

}

2.客户端接收json数据并以直方图显示代码如下:

<%@ page language="java" pageEncoding="utf-8"%>
<%@ page contentType="text/html;charset=utf-8"%>





3.实验结果图如下:

JSON—接收服务器端传来的数据_第1张图片


你可能感兴趣的:(Ajax,java)