Ajax:异步的javascript和XML,用于快速创建动态网页的技术,部分数据刷新
ajax-api:详解
- onreadystatechange:检测readState的状态
- readyState:ajax核心对象的状态
0:核心状态创建
1:调用了Open()
2:调用了Send()
3:部分完成响应(基本没意思)
4:完成响应
status:状态码(if(xmlhttp.readyState==4&&xmlhttp.status==200){})
requestText:响应回来的文本
常用的方法:
open(“请求的方式”,“请求的路径”[,“是否异步”]);
send(["参数"]):一般是post才有参数;
setRequestHeader("content-type","application/x-www-form-urlencoded"):application/x-www-form-urlencoded是form表单中的enctype属性默认值,不需要记;
- 原生Ajax的使用:
- get方式
<script type="text/javascript">
function btnClick() {
//创建核心对象
xmlhttp = null;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//编写回调函数
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText)
}
}
//open设置请求方式和请求路径
xmlhttp.open("get", "/Ajax/ajax2?username=张三");//一个servlet,后面还可以写是否同步
//send 发送
xmlhttp.send();
}
</script>
- post方式
<script type="text/javascript">
function btnClick() {
//创建核心对象
xmlhttp = null;
if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//编写回调函数
xmlhttp.onreadystatechange = function() {
/* alert(xmlhttp.readyState); */
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText)
}
/* alert(123); */
}
//open设置请求方式和请求路径
xmlhttp.open("post", "/Ajax/ajax2");//一个servlet,后面还可以写是否同步
//设置请求头
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded")
//send 发送
xmlhttp.send("username=张三");
}
</script>