JQuery 获取JSON数据方法

简述:

使用jquery从后台获取JSON数据,显示


知识点:

1. 使用了require JS 框架

2. 用Jquery的两种方法获取后台数据

1)ajax 方法,传回的都是json数据

2)getJSON, 直接封装了一些参数{command : GetRegsiterJsonData}


项目结构:

JQuery 获取JSON数据方法_第1张图片


代码:

test.html

<!DOCTYPE html>
<head>
<title>MyWebProject</title>
<meta charset="utf-8" />
<link type="text/css" href="./lib/css/jquery-ui-1.8.19.custom.css"
	rel="stylesheet" />
<script type="text/javascript" src="./lib/js/require-jquery.js"
	data-main="js/main">
	</script>

</head>
<body>
<label id="dataArea"></label>
</body>
</html>

main.js

var loadJS = [
              "jquery",
              ];

require.config({
	baseUrl : "lib/js/",
	paths: {
		"jquery": "jquery-1.8.3.min",
	}
});


//Function In main
require(loadJS, LoadData("./Test"));


//CallWebTrendsUri
function LoadData(url){
	$(function(){
		$(document).ready(function(){
			jQuery.ajax({
				type:"GET",
				url: url + "?command=GetRegsiterJsonData",
				dataType:"json",
				global:false, 
				success: function(data){
					var jsonData = "1. 用统一的ajax方法<br/>";
					var personList = data.personList;
					for(var i=0; i<personList.length; i++){
						var name = personList[i].name;
						var age = personList[i].age;
						jsonData += "name: " + name + ", age: " + age + "<br/>";  
					}
					$("#dataArea").html(jsonData + "<br/>");  
				}
			});
			
			$.getJSON(url,
					{command: "GetRegsiterJsonData"},
					function(data){
						var jsonData = "2. 用getJSON方法<br/>";
						var personList = data.personList;
						$.each(personList, function(i){
							var name = personList[i].name;
							var age = personList[i].age;
							jsonData += "name: " + name + ", age: " + age + "<br/>";  
						});
						$("#dataArea").html($("#dataArea").html() + jsonData);  
					});    
		});
	});
};


web.xml 映射servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>MyProjectWeb</display-name>
  <welcome-file-list>
    <welcome-file>test.html</welcome-file>
  </welcome-file-list>
  
  <context-param> 
    <param-name>log4jConfigLocation</param-name> 
    <param-value>/WEB-INF/log4j.properties</param-value> 
  </context-param> 
  
  
  <servlet>  
    <servlet-name>TestServlet</servlet-name>  
    <servlet-class>mwp.servlet.TestServlet</servlet-class>  
  </servlet>  
  
  <servlet-mapping>  
    <servlet-name>TestServlet</servlet-name>  
    <url-pattern>/Test</url-pattern>  
  </servlet-mapping>
  
</web-app>

下面是后台的servlet

TestServlet.java

package mwp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

class Person{  
    Person(){}  
    Person(String name, int age){  
        this.name = name;  
        this.age = age;  
    }  
    String name;  
    int age;  
}

class Register{
	String time;
	List<Person> personList;
    Register(String time){
    	this.time = time;
    	personList = new ArrayList<Person>();
    }
	void AddPerson(Person newPerson){
		this.personList.add(newPerson);
	}
}

public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getAnonymousLogger(); 
	private static Gson gson = new Gson();  


	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String command = (String)request.getParameter("command");
		logger.info("TestServlet: doGet: command: " + command);
		
		if("GetOnePersonJsonData".equals(command)){
			Person person = new Person("John", 30);  
			String personToJson = gson.toJson(person);  
			out.append(personToJson);
			logger.info("TestServlet: doGet: GetOnePersonJsonData: " + personToJson);
        }else if("GetRegsiterJsonData".equals(command)){
        	//Intialize JSON Object
        	Register register = new Register("2012/12/16");
        	Person jeremy = new Person("Jeremy", 20);
        	Person tom = new Person("Tom", 43);
        	Person mary = new Person("Mary", 33);
        	register.AddPerson(jeremy);
        	register.AddPerson(tom);
        	register.AddPerson(mary);
        	String registerToJson = gson.toJson(register);
        	//Response to frontend
        	out.append(registerToJson);
        	logger.info("TestServlet: doGet: registerToJson: " + registerToJson);
        }
	}
}


返回的JSON数据如下:

{"time":"2012/12/16","personList":[{"name":"Jeremy","age":20},{"name":"Tom","age":43},{"name":"Mary","age":33}]}


输出如下:

JQuery 获取JSON数据方法_第2张图片

你可能感兴趣的:(JQuery 获取JSON数据方法)