<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<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">
<script type="text/javascript">
var xmlHttp;
function verify(){
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
var param="username="+username+"&password="+password;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
//1.注册回调函数
xmlHttp.onreadystatechange=callback;
//2.设置连接信息
xmlHttp.open("POST","checkPost",true);
//3.设置头信息
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //这个一定要写在open方法后面
//4.发送数据,开始与服务器端交互
xmlHttp.send(param);
}
//回调函数代码如下:
function callback(){
//判断交互是否完成
if(xmlHttp.readyState==4){
//判断http的交互是否成功
if(xmlHttp.status==200){
//获取服务器端的纯文本数据
var responseText=xmlHttp.responseText;
document.getElementById("show").innerHTML=responseText;
}else{
alert("出错了");
}
}
}
</script>
</head>
<body>
<form action="" method="post">
用户名: <input type="text" name="username" id="username" ><br>
密码: <input type="password" name="password"id="password" onBlur="verify();"><br>
<div id="show"></div><br>
<input type="submit">
</form>
</body>
</html>
ajax:post 提交方案:注意的是一定要先建立连接,再设置头信息
package com.asm.servlet;
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 AjaxServletPost extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
// out.write("你输入的用户名为: + + "</font>");
out.println("你填入的结果为:<br>");
out.println("<font color='red'> username="+username+" || password="+password+"</font>");
}
}