jquery封装的ajax的请求
//页面的代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
onload = function()
{
//1、这是用jquery的ajax的post请求
//第一个参数是请求的路径,第二个参数是请求带有的参数,第三个是一个回调函数,回调函数的第一个参数是返回的数据,第二个参数是是否
//请求成功并且返回了数据,这里的get请求与post请求的方式一样,只不过将get改成post即可,但是这里一定要注意,juqery的ajax的get、
//post请求都会产生缓存,所以在后台一定要处理好缓存的问题,这种方式的请求的底层都是基于$.ajax
$.post("test?p=test",{"name":"caohuan","age":12},function(data, status){
//这是判断请求是否成功并且返回了数据
if(status == 'success')
{
alert(data);
}else
{
alert("ajax失败");
}
});
//这种方式的请求的get和post的请求的方式差不多,只不过将post改成get就行了,还有一点值得注意,这种方式请求,我们不需要担心缓存的问题
$.ajax({
type:'post',//请求的方式
url:'test?p=test',//请求的路径
dateType:'html',//这句话必须要写上,因为对于火狐而言,必须要加上这句代码才能正常运行
data:{'name':'caohuan','age':21},//请求带上的参数
success:function(data){//请求成功返回的数据
alert(data);
}
});
}
</script>
</head>
<body>
This is my JSP page. <br>
</body>
</html>
//后台的代码
package cn.itcast.servlets;
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 AjaxTestServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
//下面三句代码是处理缓存的问题
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
response.setHeader("expires", "0");
String p = request.getParameter("p");
if("test".equals(p))
{
doTest(request, response);
}
}
protected void doTest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String age = request.getParameter("age");
PrintWriter out = response.getWriter();
out.print(name+"-->" +age);
out.flush();
www.zzzyk.com
}
}
作者:ch469299503
补充:web前端 , JavaScript ,