Ajax是Asynchronous JavaScript and Xml异步的JavaScript和XML.它是一种用来改善用户体验的技术.其实质是,使用XMLHttpRequest对象异步的向服务器发请求.服务器返回部分数据,而不是一个完整的页面,以页面无刷新的效果更改页面中的局部内容.
1.Ajax设置同异步语句是:ajax.open(“Post”,url,true);其中第3个参数是设同步或者异步,true表示为异步.Ajax同步模式与异步模式的区别如下:
同步:提交请求->等待服务器处理->处理完毕返回.这个期间客户端浏览器不能做任何事.
异步:请求通过事件触发->服务器处理(这时浏览器仍然可以做其他事情)->处理完毕
在同步的情况下,js会等待请求返回,获取status.不需要onreadystatechange事件处理函数.而异步则需要onreadystatechange事件处理,且值为4再处理下面的内容.如果想获得返回值必须用同步,因为异步无法得到返回值.
2.Ajax主要功能就是提供与服务器的异步交互,比如需要输入一个用户名,在输送完毕之后,没有确认提交,Ajax可以通过异步提交来实现仅仅将输入的用户名发送到服务器数据可进行检测,然后回复是否重复.而同步提交就像注册完毕,将信息存储到数据库后提示注册成功.
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式.易于人阅读和编写,同时也易于机器解析和生成.JSON采用完全独立于语言的文本格式.
JSON最常见的用法之一,是从web服务器上读取JSON数据,将JSON数据转换为JavaScript对象,然后在网页中使用该数据.
$("#deptid")
jQuery中常见的函数如下:
1)get()取得所有匹配的DOM元素集合.
2)get(index)取得其中一个匹配的元素.index表示取得第几个匹配的元素.
3)append(content)向每个匹配的元素内部追加内容.
4)after(content)在每个匹配的元素之后插入内容.
5)html()/html(var)取得或设置匹配元素的html内容.
6)find(expr)搜索所有与指定表达式匹配的元素.
7)bind(type,[data],fn)为每个匹配元素的特定事件绑定事件处理函数.
8)empty()删除匹配的元素集合中所有的子节点.
9)hover(over,out)一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法.
10)attr(name)取得第一个匹配元素的属性值.
11)addClass(class)和removeClass(class)为指定的元素添加或移除样式.
12)css(name)访问第一个匹配元素的样式属性.
13)ajax([options])通过HTTP请求加载远程数据.
14)get(url,[data],[callback],[type])通过远程HTTP GET请求载入信息.
15)post(url,[data],[callback],[type])通过远程HTTP POST请求载入信息.
16)load(url,[data],[callback])载入远程HTML文件代码并插入至DOM中.
Q006Servlet代码如下:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequset;
import javax.servlet.http.HttpServletResponse;
public class Q006Servlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWrite out = response.getWriter();
File f = new File("tmp.txt");
long fileSize = f.length();
out.println("{'fileSize':" + fileSize + "}");
out.close();
}
}
Q006.jsp页面代码如下:
<%@ page contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>Q006title>
<script type="text/javascript">
function getXmlHttpRequest(){
var xhr = null;
if((typeof XMLHttpRequest)!='undefined'){
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
return xhr;
}
function getFileSize(){
var xhr = getXmlHttpRequest();
xhr.open('post','<%=basePath%>servlet/Q006Servlet',true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.onreadystatechange=function(){
if(xhr.readyState == 4){
var txt = xhr.responseText;
alert(txt);
var dataObj=eval("("+txt+")");//转换为JSON对象
var saleInfo = '文件大小为:'+dataObj.fileSize;
document.getElementById('d1').innerHTML=saleInfo;
}
};
xhr.send(null);
}
script>
head>
<body style="font-size:30px;" onload="getFileSize()">
<div id="d1">div>
body>
html>
web.xml配置代码如下:
<servlet>
<servlet-name>Q006Servletservlet-name>
<servlet-class>com.welkin.ajax.Q006Servletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Q006Servletservlet-name>
<url-pattern>/servlet/Q006Servleturl-pattern>
servlet-mapping>
1.编写Q007.jsp页面,代码如下所示:
<%@page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'autoCompleteInput.jsp' starting pagetitle>
<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 createXMLHttpRequest(){
if(window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlHttp == null) {
alert("不能创建XMLHttpRequest对象");
}
}
function makeRequest(){
inputField = document.getElementById("searchField");
str = inputField.value;
if(str != ""){
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
var queryString = "pre="+encodeURIComponent(str);
xmlHttp.open("POST","<%=basePath%>servlet/Q007Servlet",true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;"
xmlHttp.send(queryString);
/*
var url = "AutoCompleteServlet?pre="+escape(str);
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
*/
} else {
clearSuggestion();
}
}
function handleStateChange(){
if(xmlHttp.readyState==4){
displayNames();
} else {
alert("Not able to retrieve description : " +xmlHttp
.status+"--"+ xmlHttp.statusText);
}
}
function displayNames(){
var str = document.getElementById("searchField").value;
document.gtElementById("searchField").className="";
var popUp = document.getElementById("popups");
var results = xmlHttp.responseXML.getElementsByTagName("name");
if(results.length>0){
clearSuggestion();
var suggest = null;
for(var i = 0; i < results.length; i++){
suggest = document.createElement("div");
suggest.appendChild(document.createTextNode(results[i].firstChild.nodeValue));
suggest.onclick = makeChoice;
suggest.onmouseover="javascript:this.style.backgroundColor='orange';"
suggest.className="suggestions";
popUp.appendChild(suggest);
}
if(popUp.childNodes.length==0){
document.getElementById("searchField").className="error";
}
}
}
function makeChoice(evt){
var thisDiv= (evt) ? evt.target : window.event.srcElement;
document.getElementById("searchField").value = thisDiv.innerHTML;
document.getElementById("popups").innerHtML="";
}
function clearSuggestion(){
var models = document.getElementById("popups");
while(models.childNodes.length>0){
models.removeChild(models.childNodes[0]);
}
}
script>
<style type="text/css">
body,#searchField{
font:1.1em arial , helvetica. sans-serif;
}
.suggestions{
width:auto;
background-color: #FFE3FF;
padding: 2px 6px;
border-bottom: 1px dotted #24f;
cursor: hand;
}
.suggestions:hover{
background-color: #C8C8FC;
}
#popups{
position: absolute;
width:200px;
}
#searchField.error{
background-color: #ffc;
}
style>
head>
<body>
<br>
<br>
<br><br>
<center>
<form action="#">
<table>
<tr>
<td>输入:
td>
<td><input type="text" id="searchField" onkeyup="makeRequset()">
td>
tr>
<tr>
<td>
td>
<td>
<div id="popups">
div>
td>
tr>
table>
form>
center>
body>
html>
2.编写Q007Servlet,代码如下所示:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequset;
import javax.servlet.http.HttpServletResponse;
public class Q007Servlet extends HttpServlet {
private String[] info = {"zhang","zl","zhangli","zhao","zhaobo","\u7528\u6237","\u7528\u6237\u540D","章"."章力好啊"};
public Q007Servlet(){
super();
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
response.setHeader("Cache-Control","no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
String prefix = request.getParameter("pre");
PrintWriter out = response.getWriter();
out.println("" );
System.out.println("pre= " + prefix);
for(int i = 0; i < info.length; i++){
if(info[i].toLowerCase().indexOf(prefix.toLowerCase()) == 0){
out.println("" + info[i] + "");
System.out.println("" + info[i] + "");
}
}
out.println("");
out.flush();
out.close();
}
}
3.配置web.xml,代码如下所示:
<servlet>
<servlet-name>Q007Servletservlet-name>
<servlet-class>com.welkin.ajax.Q007Servletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Q007Servletservlet-name>
<url-pattern>/servlet/Q007Servleturl-pattern>
servlet-mapping>