1.Ajax的实现流程是怎样的?
- (1)创建XMLHttpRequest对象,也就是创建一个异步调用对象.
- (2)创建一个新的HTTP请求,并指定该HTTP请求的方法、URL及验证信息.
- (3)设置响应HTTP请求状态变化的函数.
- (4)发送HTTP请求.
- (5)获取异步调用返回的数据.
- (6)使用JavaScript和DOM实现局部刷新
<script type="text/javascript">
var httpRequest;
function checkUsername() {
if(window.XMLHttpRequest) {
//在IE6以上的版本以及其他内核的浏览器(Mozilla)等
httpRequest = new XMLHttpRequest();
}else if(window.ActiveXObject) {
//在IE6以下的版本
httpRequest = new ActiveXObject();
}
//创建http请求
httpRequest.open("POST", "Servlet1", true);
//因为我使用的是post方式,所以需要设置消息头
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//指定回调函数
httpRequest.onreadystatechange = response22;
//得到文本框的数据
var name = document.getElementById("username").value;
//发送http请求,把要检测的用户名传递进去
httpRequest.send("username=" + name);
}
function response22() {
//判断请求状态码是否是4【数据接收完成】
if(httpRequest.readyState==4) {
//再判断状态码是否为200【200是成功的】
if(httpRequest.status==200) {
//得到服务端返回的文本数据
var text = httpRequest.responseText;
//把服务端返回的数据写在div上
var div = document.getElementById("result");
div.innerText = text;
}
}
}
</script>
2.AJAX请求总共有多少种CALLBACK
Ajax请求总共有八种Callback
- onSuccess
- onFailure
- onUninitialized
- onLoading
- onLoaded
- onInteractive
- onComplete
- onException
3.XMLHttpRequest对象在IE和Firefox中创建方式有没有不同。
有,IE中通过new ActiveXObject()得到,Firefox中通过newXMLHttpRequest()得到
- 当然了,我们一般使用jquery封装好的ajax方法,那就没有那么麻烦了。
4.请解释一下 JavaScript 的同源策略。
同源策略是一种安全协议,指一段脚本只能读取来自同一来源的窗口和文档的属性。