1.什么是Ajax,以及说出几种Ajax的应用场景。
Ajax并不是一个新技术而是由JavaScript和xml结合的一种异步请求,实现局部刷新的一种技术。
2.Ajax的执行原理(原生Ajax)
编写原生Ajax的过程
function checkUserName(adminNameValue) {
//创建Ajax核心对象
var xmlRequest = new XMLHttpRequest();
//请求要访问的资源
xmlRequest.open("post","servlet/doAdmin");
//定义请求数据 注意格式
var param = "action=checkUserName&adminName="+adminNameValue;
//设置请求头部数据的内容类型及编码格式(如果使用send发送必须设置头数据格式)
xmlRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
//向服务器发送数据
xmlRequest.send(param);
//根据onreadystatechange的变量对请求消息进行处理
xmlRequest.onreadystatechange=function () {
if(xmlRequest.readyState == 4){
if(xmlRequest.status == 200 || xmlRequest.status == 304){
var responseJSON = xmlRequest.responseText;
//var responseJSON = ["Tomcat猫","23"];
//var responseJSON = {"pageSize":26,"pageData":["Tomcat猫","23"]};
alert(responseJSON);
//通过eval()函数将string字符串转换成json格式数据
var json= eval("("+responseJSON+")");
alert(json.pageSize);
alert(json.pageData[0]);
/*var subObj = document.getElementById("sub");
//如果该用户名存在返回 ok 否则返回no
if(xmlRequest.responseText == "ok"){
subObj.disabled = false;
}else{
alert("该用户名不存在");
//用户名不存在 提交按钮禁用
subObj.disabled = true;
}*/
}
}
}
}
3.Ajax的核心对象
XmlHttp是什么?
XmlHttp提供客户端同http服务器通讯的协议。
XmlHttp是一套可以在Javascript、VbScript、Jscript等脚本
语言中通过http协议传送或从接收XML及其他数据的一套API。
XmlHttp最大的用处是可以更新网页的部分内容而不需要刷新整个页面。
4.Jquery中实现Ajax的几种方式。
//param的参数类型必须是json对象格式数据 {userName:"张三",userPwd:"123"}
$.get(url,param,function(ResponseData){},"text");
$.post(url,param,function(ResponseData){},"json");
$.getJSON(url,param,function(ResponseData){});
$.ajax();
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), userPwd:123},
dataType: "json",
success: function(data){
}
});