ajax向服务端发送请求的简单使用

来源:互联网 发布:巨人网络官网 编辑:程序博客网 时间:2024/05/01 19:44

jsp界面代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'json3.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">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<c:url value='/ajax-lib/ajaxutils.js'/>"></script>


<script type="text/javascript">
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
/*
1. ajax
*/
ajax(
{
url:"<c:url value='/AServlet'/>",
type:"json",
callback:function(data) {
var str = "";
for(i in data){
var d = data[i];
str += "  "+d.name + ", " + d.age + ", " + d.sex;
}
document.getElementById("h3").innerHTML = str;
}
}
);
};
};
</script>
  </head>
  
  <body>
<%-- 点击按钮后,把服务器响应的数据显示到h3元素中 --%>
<button id="btn">点击这里</button>
<h1>显示自己封装的ajax小工具</h1>
<h3 id="h3"></h3>
  </body>
</html>



Servlet代码:


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 com.luowg.demo1.Person;


public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*
* 向客户端发送json串
*/
// String str = "{\"name\":\"zhangSan\", \"age\":18, \"sex\":\"male\"}";
Person p1 = new Person("张三", 23, "男");
Person p2 = new Person("李四", 32, "女");
List<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
System.out.println(JSONArray.fromObject(list).toString());
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(JSONArray.fromObject(list).toString());


}
}


记得在web.xml注册servlet 哦 (*^__^*)


0 0
原创粉丝点击