AJAX   :Asynchronous JavaScript and XML 异步的javascript 和xml

优点 : 在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分数据

不需要任何的浏览器插件,但需要用户允许javascript在浏览器上执行

应用:运用XHTML+CSS来表达资讯   javascript操作DOM(Document Object Model)

XMLHttpRequest是ajax的基础

现代浏览器(IE7、FIREFOX、CHROME、safari 还有Opera)旧代(IE5、IE6)

语法不同 :variable = new XMLHttpRequest();

Variable = new ActiveXObject(“Microsoft.XMLHTTP”);

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

向服务器发送请求:   XMLHttpRequest对象的open() send()方法

xmlhttp.open(method, url, async):method--get或者post类型

Url --文件在服务器上的位置

Async:boolean值  true  (异步) false 同步

xmlhttp. Send(String)    :String ---post请求

Get方法更简单方便   post:无法使用缓存文件、发送大量数据

例子:get:xmlhttp.open(“get” , “demo_get.html” , true);

xmlhttp.send();

Post: xmlhttp.open(“post” , “demo_post.html” , true);

xmlhttp.setRequestHeader(“content-type” ,“application/x-www-form-urlencoded”);

//向请求添加HTTP头  header 头的名称  value  值

xmlhttp.send(“fname = Bill & lname = gates”);

Async = true : 请规定在响应处于onreadystatechange 时间中 的就绪状态

xmlhttp.onreadystatechange = function(){

if(xmlhttp.readyState == 4 && xmlhttp.status == 200){

document.getElementById(“muDiv”).innerHTML = xmlhttp.responseText;

}

}

xmlhttp.open(“get” , “test.txt” , true);

xmlhttp.send();

服务器响应: XMLHttpRequest对象的responseText  或者 responseXML

字符串响应数据        XML形式响应

每当readystate改变的时候,就会触发onreadystatechange事件

Readystate存有XMLHttpRequest的状态  0-4

0: 请求未初始化          1:服务器连接已建立

2:请求已接受       3:请求处理中    4:请求已完成,且响应已就绪

Status: 200  “OK” ;  404: 未找到页面

例子:

function showHint(str)

{

var xmlhttp;

if (str.length==0)

{

document.getElementById("txtHint").innerHTML="";

return;

}

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("txtHint").innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET","gethint.asp?q="+str,true);

xmlhttp.send();

}

代码解释: 如果输入框为空 length==0 清空txthint占位符的内容,并退出函数

如果不为空,执行任务:

创建XMLHttpRequest对象 ,当服务器响应就绪时执行函数

把请求发送到服务器上的文件,  注:url中带有个参数q

例子:简化版

HTML

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

<script type="text/javascript" src="js/ajax.js"></script>

<script type="text/javascript">

window.onload=function() {

document.getElementById("username").onblur=function() {

sendAjax("POST", "register.sxt", "username="+this.value, function(result) {

// 向span中显示信息

if(result == "yes") {

document.getElementById("uspan").innerHTML="√";

} else {

document.getElementById("uspan").innerHTML="×";

}

});

};

};

</script>

</head>

<body>

<input type="text" name="username" id="username" /><span id="uspan"></span>

</body>

</html>

Js

function sendAjax(method, url, body, success) {// 钩子函数, 回调函数

var xmlHttp;

if(window.XMLHttpRequest) {

xmlHttp = new XMLHttpRequest();

} else {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

}

xmlHttp.onreadystatechange = function() {

if(xmlHttp.readyState == 4) {

if(xmlHttp.status == 200 || xmlHttp.status == 304) {

// 成功时调用函数

success(xmlHttp.responseText);

}

}

};

xmlHttp.open(method, url);

if(method == "POST") {

// 设置请求头信息, 表示提交数据时按照表单的方式提交

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

}

xmlHttp.send(body);

}

如果加了数据库内容:

@WebServlet("/register.sxt")

public class RegisterServlet extends HttpServlet {

@Override

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

String username = req.getParameter("username");

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

String sql = "select count(*) from users where username=?";

try {

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test401", "root", "root");

pstmt = conn.prepareStatement(sql);

pstmt.setString(1, username);

rs = pstmt.executeQuery();

if(rs.next()) {

if(rs.getInt(1)>0) {

resp.getWriter().print("no");

} else {

resp.getWriter().print("yes");

}

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

rs.close();

pstmt.close();

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

最新文章

  1. Nginx+FastCGI运行原理
  2. Centos7下安装mono3.10.0
  3. 【原创】数据挖掘案例——ReliefF和K-means算法的医学应用
  4. C++中的静态绑定和动态绑定
  5. Housse Robber II | leetcode
  6. JS This关键字
  7. OpenJudge/Poj 1191 棋盘分割
  8. HDU-2576 Tug of War
  9. for循环++i效率
  10. class Core&lt;T&gt; where T : class, new() 求解
  11. Concepts and Tricks In CNN
  12. Scrapy-简单介绍
  13. C 语言内存区域分配(进程的各个段)详解
  14. 题解 P5065 【[Ynoi2014]不归之人与望眼欲穿的人们】
  15. centos下搭建sockets5代理
  16. Genomic signatures of evolutionary transitions from solitary to group living(独居到社会性的转变)
  17. angular中的jqLite所包含的jquery API
  18. Lingoes 一款功能强大、简明易用的多语言词典和文本翻译软件
  19. Gradle Goodness: Group Similar Tasks
  20. Bootstrap学习笔记面板(Panels)

热门文章

  1. 数据库字段值为null利用setInc方法无法直接写入
  2. Python入门-内置函数二
  3. 【Android】13.0 UI开发(四)——列表控件RecyclerView的横向布局排列实现
  4. bat中实现代码拷贝到指定目录后启动命令行并更改默认路径
  5. &lt;Android 基础(十九)&gt; CoordinatorLayout
  6. vim使用方法----转载
  7. 【JAVA语法】03Java-继承性
  8. Vue2.0的动画效果
  9. Fiddler给网站“优化”
  10. spark出现task不能序列化错误的解决方法