jsp页面(Ajax)
My JSP 'ajax1.jsp' starting page//文档加载完毕后执行
window.onload = function() {
var btn = document.getElementById("btn");
//给按钮的点击事件注册监听
btn.onclick = function() {
/*
* ajax四步操作,得到服务器的响应
* 把响应结果显示到h1元素中
*/
//1. 得到异步对象
var xmlHttp = createXMLHttpRequest();
/*
2. 打开与服务器的连接
* 指定请求方式
* 指定请求的URL
* 指定是否为异步请求
*/
/************修改open方法,指定请求方式为POST**************/
xmlHttp.open("POST", "", true);
/************设置请求头:Content-Type************/
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
/*
* 3. 发送请求
* GET请求没有请求体,但也要给出null,不然FireFox可能会不能发送!
*/
/**********发送时指定请求体***********/
xmlHttp.send("username=QQ群:Java技术之信仰 557254530&password=123");
/*
* 4. 给异步对象的onreadystatechange事件注册监听器
*
*/
//当xmlHttp的状态发生变化时执行
xmlHttp.onreadystatechange = function() {
// 双重判断:xmlHttp的状态为4(服务器响应结束),以及服务器响应的状态码为200(响应成功)
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
// 获取服务器的响应结束
var text = xmlHttp.responseText;
// 获取h1元素
var h1 = document.getElementById("h1");
h1.innerHTML = text;
}
};
};
};
点击这里
servlet处理页
package com.ajax.data;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet
* 响应text文本:方式POST
* 解决中文乱码
*
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("username");
//解决中文乱码
String strNmae = new String(name.getBytes("ISO-8859-1"),"UTF-8");
//byte[] n = name.getBytes("ISO-8859-1");
//String strNmae = new String(n,"UTF-8");
System.out.println("doPost HELLO AjAX!"+strNmae);
response.getWriter().print("doPost hello ajax!!!"+strNmae);
}
}
后台输出:
doPost HELLO AjAX! QQ群:Java技术之信仰 557254530