JavaScript Ajax 与服务器通信

XMLHttpRequest对象

-常用方法-:

open("method","URL",是否异步默认为true,"用户名","密码") 设置进行异步请求目标的URL

send(content); content可以是DOM对象的实例、输入流、字符串、null

setRequestHeader("header","value") 为请求的HTTP头设置值

abort() 停止或放弃当前异步请求

getResponseHeader("headerLabel") 以字符串形式返回指定的HTTP头信息

getAllResponseHeaders() 以字符串形式返回完整的HTTP头信息,其中包括Server、Date、Content-Type、Content-Length

-常用属性-:

【onreadystatechange】 用于指定状态改变时所触发的时间处理器。在Ajax中,每个状态改变时都会触发这个时间处理器,通常会调用一个JavaScript函数

(实例化好的XMLHttprequest(非IE)对象或ActiveX(IE)对象)http_request.onreadystatechange=getResult;

【readyState】获取请求的状态,该属性有5个属性值 0-未初始化 1-正在加载 2-已加载 3-交互中 4-完成

【responseText】 获取服务器的响应,表示为字符串

【responseXML】 获取服务器的相应,表示为XML。这个对象可以解析为一个DOM对象

【status】 返回服务器的HTTP状态码,常用的状态有 200-表示成功 202-表示请求被接受但尚未成功 400-错误的请求 404-文件未找到 500-内部服务器错误

【statusText】 返回HTTP状态码对应的文本,如OK或Not Fount(未找到)等

 

---使用Ajax与服务器---i

点击index.jsp表单中检测用户名按钮,调用JS里checkUer方法,再通过Ajax与Servlet通信,检测用户是否存在,并在页面显示结果。

1.编写index.jsp及JavaScript Ajax

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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">
<script type="text/javascript">
function checkUser(userName){
if(userName.value==""){
alert("请输入用户名");
userName.focus();
return;
}else{
createRequest("ChecheUserServlet?userName="+userName.value);
}
}
function createRequest(url){//访问服务器
http_request = false;
if(window.XMLHttpRequest){//非IE浏览器
http_request = new XMLHttpRequest();
}else if(windows.ActiveXObject){//IE浏览器
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){

}
}
}
if(!http_request){
alert("不能创建XMLHttpReuqest对象实例!");
return false;
}
http_request.onreadystatechange = getResult;//回调函数
http_request.open("GET", url, true);//GET方式异步请求URL(servlet或者JSP或者其它...)
http_request.send(null);//发送参数
http_request.open(method, url, async, username, password)
}
function getResult(){//处理服务器的响应
if(http_request.readyState==4){//请求完成
if(http_request.status==200){//请求成功
document.getElementById("message").innerHTML = http_request.responseText;
document.getElementById("message").style.display="block";
//document.getElementById("checkedName").style.display="none";
}else{
alert("您所请求的页面有错误");
}
}
}
</script>
</head>

<body>
<form name="register" action="" method="get">
<table cellpadding="0" cellspacing="0" style="width: 500px;height: 200px;">
<tr>
<td width="30%" align="right">用户名:</td>
<td width="35%"><input type="text" name="username"></td>
<td width="35%">
<input type="button" name="checkedName" id="checkedName" value="检查用户名" οnclick="checkUser(register.username);" style="float: left;">
<div id="message" style="float:left; display: none;font-size: 12px;font-family: sans-serif;line-height: 20px;"></div>
</td>
</tr>
<tr>
<td align="right">密码:</td>
<td colspan="2"><input type="password" name="password"></td>
</tr>
<tr>
<td align="right">确认密码:</td>
<td colspan="2"><input type="password" name="confirmPwt"></td>
</tr>
<tr>
<td align="right">E-mail:</td>
<td colspan="2"><input type="text" name="email"></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" name="submit" value="注册" style="margin-left: 30%;">
</td>
</tr>
</table>
</form>
</body>
</html>

2.编写CheckUserSevlet,注解配置CheckUserServlet.

package com.smxy.lxz.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ChecheUserServlet")
public class ChecheUserServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String[] user = {"李雄资","lxz","lixiongzi"};

response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();

String userName = new String(request.getParameter("userName").getBytes("ISO8859-1"),"UTF-8");
Arrays.sort(user);
int result = Arrays.binarySearch(user, userName);
if(result>=0){
out.write("已存在!");
}else{
out.write("可以使用!");
}
out.flush();
out.close();
}

/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}

}

【效果】

 

转载于:https://www.cnblogs.com/ZimSionLi/p/4767951.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值