Java基础96 ajax技术的使用

时间:2023-03-09 20:17:12
Java基础96 ajax技术的使用

本文知识点(目录):

1、ajax的概念
   2、使用ajax技术获取服务端的数据_实例
   3、使用ajax技术检查用户名是否已存在_实例
   4、使用ajax技术验证登录页面的用户名和密码_实例



1、ajax的概念

ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
  ajax的全称是Asynchronous JavaScript and XML,即异步JavaScript+XML。它并不是新的编程语言。

1.2、XMLHttpRequest 对象

 var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest(); //IE7+,Firefox,Chrome,Opera,Safari...
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); //IE6,IE5...
}

Java基础96 ajax技术的使用

1.3、XMLHttpRequest 发送请求

 request.open("GET","get.php",true); //方式1
request.send(); request.open("POST","post.php",true); //方式2
request.send(); request.open("POST","create.php",true); //方式3
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("name=jack&sex=male");

1.4、ajax的优点和缺点

  优点:在不更新整个页面的前提下维护数据,web应用程序更为迅捷的回应用户动作。
  缺点:
  1.破坏了浏览器的后退功能。
      解决方案:HTML5创建或使用一个隐藏的iframe来重现页面上的变更。
  2.破坏加入收藏书签功能。
      解决方案:
        1.HTML5用URL片段标识符来保持追踪,允许用户回到指定的某个应用程序状态。
        2.直接操作浏览历史,以字符串的形式存储网页状态,将网页加入网页书签、收藏夹时状态会被隐形保留。

除此之外,ajax还需要注意的一点是:网络延迟,即用户发出请求到服务器回应之间的间隔。
  处理方式是用可视化组件告诉用户系统正在进行的后台操作和正在读取数据和内容。

2、使用ajax技术获取服务端的数据_实例

Java基础96 ajax技术的使用获取服务器test.txt中的信息        Java基础96 ajax技术的使用

ajax.html 页面(ajax)

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ajax.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body>
<input type="button" value="获取服务端数据" onclick="getData()">
</body>
<script>
//XMLHttpRequest:是js中唯一能够跟后台进行交互的对象
var xhr;
function getData(){
//1.判断浏览器,根据浏览器对xmlhttpRequest的支持创建对象
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
//IE5 IE6
xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
//2.打开一个链接(提交方式,请求资源,是否异步请求)
xhr.open('get','test.txt',true);
//3.当请求状态发生变化时触发回调函数
xhr.onreadystatechange=callback;//callback:回调函数
//4.发送请求
xhr.send();
} function callback(){//回调函数
//判断请求状态是否完成
if(xhr.readyState==4){
//判断响应是否成功
if(xhr.status==200){
//获取服务端响应的数据
var msg=xhr.responseText;
alert(msg);
}
}
}
</script>
</html>

结果图

Java基础96 ajax技术的使用

3、使用ajax技术检查用户名是否已存在_实例

frame.js 文件

 function $(id){
return document.getElementById(id);
} function elesByName(name){
return document.getElementsByName(name);
} function elesByTag(name){
return document.getElementsByTagName(name);
} function createEle(name){
return document.createElement(name);
} //封装trim函数(去除空格)
String.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g,"");
};

CheckUnameServlet 类

 package com.shore.a_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 CheckUnameServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//假设数据库包含如下用户
String[] names = {"admin","softeem","users1","rose","jack"};
//获取要检查的用户名
String name = request.getParameter("uname");
System.out.println("进入后台:"+name);
//假设该用户不存在
boolean flag = false;
for(String s:names){
if(s.equals(name)){
flag = true;
break;
}
}
PrintWriter out=response.getWriter();
if(flag){
//账号不可用(数据库中已存在)
out.println("no");
}else {
//可以注册
out.println("yes");
}
out.flush();//刷新
out.close();//关闭资源
}
}

index.html 页面(ajax)

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="js/frame.js"></script>
</head>
<body>
用户名:<input type="text" id="uname"/>
<input type="button" value="检查用户名" onclick="check()">
<span id="msg"></span>
</body>
<script>
var xhr;
//1.判断浏览器
function getXhr(){
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function check(){
getXhr();
//获取用户名
var name=$('uname').value;
//2.打开一个链接
xhr.open('get','CheckUnameServlet?uname='+name,true);
//3.当请求状态发生改变时触发回调函数
xhr.onreadystatechange=callback;
//4.发送
xhr.send();
} function callback(){
//判断请求是否完成
if(xhr.readyState==4){
//判断响应是否完成
if(xhr.status==200){
//获取服务端相应数据
var data=xhr.responseText;
if(data.trim()=="yes"){
$('msg').innerHTML="<font color='green'>账号可用!</font>";
}else{
$('msg').innerHTML="<font color='red'>账号已被注册!</font>";
}
}
}
}
</script>
</html>

结果图

Java基础96 ajax技术的使用

4、使用ajax技术验证登录页面的用户名和密码_实例

ServiceModel 实体类

 package com.shore.util;

 public class ServiceModel {
private int code; //状态码
private String msg;//提示信息 public ServiceModel() {
}
public ServiceModel(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

LoginServlet 类

 package com.shore.a_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; import com.shore.util.ServiceModel; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String uname=request.getParameter("uname");
String upass=request.getParameter("upass"); System.out.println(uname+"---"+upass);
PrintWriter out=response.getWriter();
//创建业务模型对象
ServiceModel model=new ServiceModel();
if("admin".equals(uname)){
if("123456".equals(upass)){
model.setCode(1);
model.setMsg("登录成功");
}else{
model.setCode(0);
model.setMsg("密码错误");
}
}else{
model.setCode(-1);
model.setMsg("账号不存在");
}
//json数据格式
String msg="{'code':'"+model.getCode()+"','msg':'"+model.getMsg()+"'}";
out.println(msg);//传到页面去
out.flush();
out.close();
}
}

ajax_post.html 页面(ajax)

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ajax_post.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="js/frame.js"></script>
</head> <body>
<div>
<table id="login_form">
<caption>用户登陆</caption>
<tr>
<th colspan="2"><span id="msg"></span></th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" id="uname"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="upass"></td>
</tr>
<tr>
<td>
<input type="button" value="登陆" onclick="login()"/>
</td>
</tr>
</table>
<span id="ok"></span>
</div></body>
<script>
var xhr;
function login(){
var name = $("uname").value;
var pass = $("upass").value;
//拼接需要提交的数据 "uname=admin&upass=123456"
var query = "uname="+name+"&upass="+pass;
//对需要提交的数据进行转码(防止乱码)
query=encodeURI(query);
//1.判断浏览器
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.打开连接
xhr.open('post','LoginServlet',true);
//3.当请求状态发生改变时触发回调函数
xhr.onreadystatechange=handlerData;
//设置请求头信息(对于post)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//4.发送请求(参数为需要提交的数据)
xhr.send(query);
}
function handlerData(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = xhr.responseText;
data = data.trim();
//alert(data);//弹出框
//把json字符串转为javascript对象
data=eval("("+data+")");
if(data.code==1){
$("login_form").style.display="none";
$("ok").innerHTML="<font color='green'>"+data.msg+"</font>";
}else if(data.code==0){
$("msg").innerHTML="<font color='red'>"+data.msg+"</font>";
}else{
$("msg").innerHTML="<font color='red'>"+data.msg+"</font>";
}
}
}
</script>
</html>

结果图

Java基础96 ajax技术的使用

Java基础101 Struts2下的 jquery+ajax+struts 技术实现异步刷新功能

ajax技术 更详细的内容:https://www.cnblogs.com/dulmcat/p/5812062.html

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/10708447.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

相关文章