Ajax不是某种编程语言,而是一种在无需重新加载整个网页的情况下能够更新部分网页的技术。
下面就是在对ajax基础学习的总结。
//注意:代码和样式不能兼容低版本IE
//通过AJAX获取命中提示内容
document.getElementById('keyword').oninput = function() {
var keyword = this.value;
//典型的AJAX编程模板
//1.创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//2.open操作初始化请求信息
xhr.open('GET', 'a.php', true);
//3.监听事件处理响应结果
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
console.log(a);
}
}
//4.send操作发出请求
xhr.send();
}
//处理响应结果
//创建对象
//IE7+和其他浏览器都支持
//XMLHttpRequest 有level1和level2两个版本
//现代浏览器都支持xhr level 2,支持情况参考相关资料
//xhr level2兼容xhr1并新增;
//1.timeout支持
//2.CORS 跨域支持
//3.upload 文件上传支持
function creatXHR() {
return new XMLHttpRequest();
}
//创建对象,兼容版
//IE6+ Msxml2.XMLHTTP
//<IE6 Microsoft.XMLHTTP
function creatXHR2() {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
}
//请求的发起
function textcreatXHR2() {
var xhr = creatXHR2();
xhr.open('POST', 'http://test/keyword/hit', true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader('test', 'value');
xhr.send(JSON.stringify({
keyword: 'c';
other: 'test'
})); //urlencoded
//超时设置
xhr.timeout = 5000;
xhr.ontimeout = function() {
console.log('timeout');
}
//仅xhr level2支持
xhr.οnlοad=function(){
if (xhr.status==200) {
console.log('load,%s',xhr.responseText);
}
}
//传统方式
xhr.onreadystatechange=function(e){
if (xhr.readystate===4&&xhr.status==200) {
console.log(xhr.responseText);
console.log(xhr.responseXML);
}
//readystate 5种状态
//0:未初始化
//1:连接建立、请求发出
//2:服务器返回响应
//3:交互(处理响应数据)
//4:完成:数据可交付客户端使用
}
}
//jQuery实现AJAX GET
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
type:"GET",
url:"service.php?numbei="+$("#keyword").val(),
dataType:"json",
success:function(data){
if (data.success) {
$("#searchResult").html(data.msg);
}else{
$("#searchResult").html("出现错误:"+data.msg);
}
}
})
})
//jQuery实现AJAX POST
$("#save").click(function(){
$.ajax({
type:"POST",
url:"service.php",
datatype:"json",
data:{
name:$("#staffName").val(),
number:$("#staffNumber").val(),
sex:$("#staffSex").val(),
job:("#staffJob").val(),
}
success:function(data){
if (data.success) {
$("#searchResult").html(data.msg);
}else{
$("#searchResult").html("出现错误:"+data.msg);
}
}
})
})
})