AJAX入门
AJAX 全名为 Asynchronous JavaScript And XML,可以不刷新网页达到网页部分更新的
先看看案例:不刷新页面验证账号
html部分:
<span>输入账号 :</span>
<input id="name" name="name" onkeyup="check()" type="text">
<span id="checkResult"></span>
<script>
var xmlhttp;
function check(){
var name = document.getElementById("name").value;
var url = "https://how2j.cn/study/checkName.jsp?name="+name;
xmlhttp =new XMLHttpRequest();
xmlhttp.onreadystatechange=check_Result; //响应函数
xmlhttp.open("GET",url,true); //设置访问的页面
xmlhttp.send(null); //执行访问
}
function check_Result(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
document.getElementById('checkResult').innerHTML=xmlhttp.responseText;
}
</script>
jsp部分:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false"%>
<%
String name = request.getParameter("name");
if("abc".equals(name))
out.print("<font color='red'>已经存在</font>");
else
out.print("<font color='green'>可以使用</font>");
%>
接下来我们就讲讲这些代码怎么实现ajax的
首先我们先onkeyup , onkeyup 事件会在键盘按键被松开时发生
然后我们看到XMLHttpRequest 对象,XMLHttpRequest 对象用于在后台与服务器交换数据。能做到:
- 在不重新加载页面的情况下更新网页
- 在页面已加载后从服务器请求数据
- 在页面已加载后从服务器接收数据
- 在后台向服务器发送数据
接下来是onreadystatechange,onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码。
最后通过open函数设置背后的这个小线程,将要访问的页面url,通过send函数进行实际的访问
send函数中的null表示没有参数,因为参数已经通过“GET" 方式,放在url里了。
只有在用"POST",并且需要发送参数的时候,才会使用到send。
类似这样:
xmlhttp.send("user="+username+"&password="+password)
于是,我们就简单的了解了ajax