Ajax:页面无刷新请求数据
原生js实现ajax(简单封装)
var ajax = {
//创建xmlHttpRequest对象
createXmlHttpRequest: function(){
var xhr = null;
try{
xhr = new XMLHttpRequest();//firefox Opera 8.0+, Safari
}catch(e){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");//IE 6.0+
}catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");//IE 5.5+
}
}
return xhr;
},
/*
* method -> 请求方式 post/get
* url -> 请求的资源路径url
* dataPost -> get 如 ?name='ys'&age=12;
* post如 {'data':12,'age':12};
* callback ->回调函数
**/
judgeXmlHttpRequest: function(method, url, callback, dataPost){
var xhr = this.createXmlHttpRequest();//先创建
if(xhr){
var resData = undefined;
//true表示异步请求
xhr.open(method, url ,true);
if(method === 'post'){
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(dataPost);
}else{
xhr.send(null);
}
//readyState表示请求/响应过程的状态0-4
//readyState每次变化,都会触发readystatechange事件
xhr.onreadystatechange = function(){
//
if(xhr.readyState === 4 && xhr.status === 200){
//resData = xhr.responseXML; 响应XML数据
//响应文本数据
resData = xhr.responseText;
//回调函数
callback(resData);
}
}
}
}
}
说明:ajax.judgeXmlHttpRequest()方法有4个形参,get方法只用了3个,不是语法错误,JavaScript引擎将会忽略第四个形参
调用代码
get方法
ajax.judgeXmlHttpRequest('get', 'index.php', function(data){
alert(data); //这是服务器返回的数据
})
post方法
var dataJson = {
name: 'ys',
age: 123
}
ajax.judgeXmlHttpRequest('post', 'index.php', function(data){
alert(data); //这是服务器返回的数据
},dataJson)
说明:
在form元素中,enctype表明提交数据的编码格式
- content-type:application/x-www-form-urlencoded,(标准编码)窗体数据被编码为名称/值对(和post封装的json一样);
- content-type:multipart/form-data, 窗体数据被编码为一条消息,不对字符编码。(上传文件必须该编码方式)
- content-type:text/plain: 窗体数据以纯文本形式进行编码
而这里的post请求采用了默认的application/x-www-form-urlencoded进行编码,编码+消息体,使得post更安全