您的位置:首页 > Web前端 > JavaScript

json+servlet

2016-05-13 00:00 393 查看
摘要: json+servlet

json+servlet----------------------

-----------------------------页面--------------------------------------

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'jsonTest.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<script type="text/javascript">
function createXmlHttp(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
var xmlHttp;
function ajaxObject(){
xmlHttp=createXmlHttp();
var url="/pageWeb/TestJsonServlet"
xmlHttp.open("get", url, true);
xmlHttp.onreadystatechange = updatePage;
// xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlHttp.send(null);
}

function updatePage() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var response = xmlHttp.responseText;
var jsons=eval("(" + response + ")");
for(var i=0;i<jsons.length;i++){
alert(jsons[i]);
}
} else
alert("status is " + xmlHttp.status);
}
}
</script>
<body>
<input type="button" value="点击" onclick="ajaxObject();">
</body>
</html>

-----------------------------------servlet-----------------------------------------

public class TestJsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
List list=new ArrayList();
list.add("ly");
list.add("ly1");
list.add("ly2");
list.add("ly3");
list.add("ly4");
list.add("ly5");
PrintWriter out=response.getWriter();
JSONArray JList=JSONArray.fromObject(list);
String jsonS=JList.toString();
out.write(jsonS);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: