阿贾克斯(AJAX)

AJAX   Asynchronous JavaScript and XML 异步的javascript xml

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

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

应用:运用XHTML+CSS来表达资讯   javascript操作DOMDocument Object Model

XMLHttpRequestajax的基础  

  现代浏览器(IE7FIREFOXCHROMEsafari 还有Opera)旧代(IE5IE6

 语法不同 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 --文件在服务器上的位置

    Asyncboolean值  true  (异步) false 同步

      

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

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

例子:getxmlhttp.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:请求已完成,且响应已就绪

 Status200  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();

}

}

}

}

原文地址:https://www.cnblogs.com/wxj-106/p/7729859.html