首先主要是将javascript版本ajax做下注释:ajax异步刷新主要是将所需条件拼成字符串传入后台,处理之后,直接调用回调函数将所得数据返还给页面,并加以显示,因为还在本页面,所以不用刷新页面,懂了了吧,本篇也用encodeURI对字符串做了加密,并在类里做了解码,其中需要一些注意的地方在源码里做了注释。get/post两种提交方式,但get提交容易乱码,一定多加注意
jsp页面:
复制代码 代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
用户:
密码:
这里是servlet/action Java代码:
复制代码 代码如下:
package com.cstp.javascript;
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;
@SuppressWarnings("serial")
public class AjaxServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//设置编码,防止乱码
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//接收参数
String msg=request.getParameter("msg");
if(msg.equals("gets")){
// String name=new String(request.getParameter("name").getBytes("ISO8859-1"), "UTF-8"); //一次编码,java里进行解码操作
String name=java.net.URLDecoder.decode(request.getParameter("name"),"utf-8"); //decode解码页面必须两次编码,java里进行解码操作
String pwd=request.getParameter("pwd");
System.out.println(name+","+pwd);
PrintWriter out = response.getWriter();
out.println("ajax响应get,结果返回"+name+","+pwd);
}else if(msg.equals("posts")){
String name=new String(request.getParameter("name").getBytes("utf-8"), "UTF-8"); //一次编码,java里进行解码操作
String pwd=request.getParameter("pwd");
System.out.println(name+","+pwd);
PrintWriter out = response.getWriter();
out.println("ajax响应post,结果返回"+name+","+pwd);
}
}
}
上面是javascript版ajax,下面将喜欢jquery版的也分享给JQ友们:
页面上:
复制代码 代码如下:
后台:servlet/action里
类里对数据处理的方法同上,就不再累赘了