JqueryServlet.java
jqueryjson.jsp
package com.fayhong.util;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.fayhong.service.basicdata.BasicDataService;
public class JqueryServlet extends HttpServlet {
public BasicDataService basicDataService;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
basicDataService=(BasicDataService)wac.getBean("basicDataService");
resp.setContentType("text/html;charset=UTF-8");
resp.setHeader("Cache-Control", "no-cache");
JSONObject json = new JSONObject();
List list=basicDataService.findCountry(null, null);
try{
JSONArray members = new JSONArray().fromObject(list);
json.put("country", members);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(json.toString());
resp.getWriter().write(json.toString());
}
}
jqueryjson.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<title>JSON</title>
<script src="scripts/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery/json.js" type="text/javascript"></script>
<script>
$(document).ready(function (){
var query="test";
$.getJSON("jquery",null,function call(data){ wirteHtml(data);})
});
function wirteHtml(data){
$.each(data.country,function(idx,item){
if(idx==0){
return true;//同countinue,返回false同break
}
alert(item.englishName);
});
alert(data.country.length);
alert(data.country[0].englishName);
}
</script>
</head>
<body>
</body>
</html>