关于Ajax的写法
Ajax 即“Asynchronous Javascript And XML " (异步JavaScript 和 XML ),能够在无需重新加载整个网页的情况下,更新部分网页(异步更新)。
- jq请求Ajax
类型 | 内容 | 类别 | 解释 |
---|---|---|---|
url | 地址 | 相对地址/绝对地址 | 例子: url: ‘http://jingdong.index.json’、url: ‘/request/ajaxtest’、url: ‘request/ajaxtest’ |
dataType | 数据类型 | json | 一般都是json数据类型 |
type | 请求类型 | GET/POST | GET请求在地址栏中有显示你的请求信息;POST请求不会,所以POST请求安全性比较高,当你要发送账号和密码时,最好使用POST请求; |
timeout | 超时 | number | 当发送请求超过number秒后,还没接受到信息就报错error |
注:请求回来的数据是json格式的,需要将数据转成js对象格式才能被浏览器所识别,所以要调用JSON.parse(data)函数
$.ajax({
url:'3.query.php',//地址
dataType:'json',//数据类型
type:'GET',//类型
timeout:2000,//超时
//请求成功
success:function(data,status){
var res = data;
//alert(data);
res = JSON.parse(res); //解析数据
//alert(status);
},
//失败/超时
error:function(XMLHttpRequest,textStatus,errorThrown){
if(textStatus==='timeout'){
alert('請求超時');
setTimeout(function(){
alert('重新请求');
},2000);
}
//alert(errorThrown);
}
})
- 原生js封装Ajax
onreadystatachange:存储函数,每当readyStata属性改变时,就会调用该函数。
readyStata:有XMLHttpRequest的状态(0到4)
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,响应已就绪
status:200表示"ok",404表示”未找到页面"
status==404,表示找不到网页(no find)
使用post提交时,要设置表单提交时的内容类型
xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)
POST提交的数据有一定的格式,所以需要格式话数据后才能提交
//调用Ajax函数
ajax({
url: '',
type: 'GET/POST',
dataType: 'json',
data: {name: "hello",age: "12"},
success:function(response,xml){
//请求成功后执行的代码
},
error: function(status){
//请求失败后执行的代码
}
});
//封装ajax
function ajax(options){
options = options||{}
options.type = (options.type||'GET').toUpperCase()
options.dataType = options.dataType || 'json'
params = formatParams(options.data)
var xhr
//非ie6
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest()
}else{
//ie6及以下版本浏览器
xhr = ActiveXObject('Microsoft.XMLHTTP')
}
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
var status = xhr.status
if(status>=200 && status<=300)
{
options.success && options.success(xhr.responseText,xhr.responseXML)
}else{
options.error&&options.error(status)
}
}
}
if(options.type == 'GET'){
xhr.open('GET',options.url+'?'+params,true)
xhr.send(null)
}else if(options.type == 'POST'){
xhr.open('POST',options.url,true)
//设置表单提交时的内容类型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(params)
}
}
//格式化数据
function formatParams(data){
var arr = [];
for(var name in data){
arr.push(encodeURIComponent(name)+'='+encodeURIComponent(data[name]))
}
arr.push(('v='Math.random()).replace('.',''))
return arr.join('&')
}