/*
* JS封装ajax()函数使用方法:
*
*ajax({
* method: "GET"/"POST",
* url: "test.php",
* async: true异步/false同步,
* data:{
* name: "leo",
* sex: "男",
* },
* success:function(res){
* console.log(res);
* }
* })
*
* */
function ajax(opt) {
// 初始化参数
opt = opt || {};
opt.method = opt.method.toUpperCase() || "POST";
opt.url = opt.url || "";
opt.async = opt.async || true;
opt.data = opt.data || {};
opt.success = opt.success || function () {};
//处理XMLHttp中IE6及一下的兼容
var xmlHttp = null;
if(XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// 处理需要传递的数据
var paras = [];
for(var key in opt.data){
paras.push(key + "=" + opt.data[key]);
}
var postData = paras.join("&");
//处理'POST'和'GET'两种方式提交的差异
if(opt.method.toUpperCase() === "POST"){
xmlHttp.open(opt.method,opt.url,opt.async);
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}else if(opt.method.toUpperCase() === "GET"){
xmlHttp.open(opt.method,opt.url+"?"+ postData + new Date().getTime(),opt.async);
xmlHttp.send(null);
}
//返回的数据状态正确,则给opt.success()传回数据
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
opt.success(xmlHttp.responseText);
}
}
}
* JS封装ajax()函数使用方法:
*
*ajax({
* method: "GET"/"POST",
* url: "test.php",
* async: true异步/false同步,
* data:{
* name: "leo",
* sex: "男",
* },
* success:function(res){
* console.log(res);
* }
* })
*
* */
function ajax(opt) {
// 初始化参数
opt = opt || {};
opt.method = opt.method.toUpperCase() || "POST";
opt.url = opt.url || "";
opt.async = opt.async || true;
opt.data = opt.data || {};
opt.success = opt.success || function () {};
//处理XMLHttp中IE6及一下的兼容
var xmlHttp = null;
if(XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}else{
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
// 处理需要传递的数据
var paras = [];
for(var key in opt.data){
paras.push(key + "=" + opt.data[key]);
}
var postData = paras.join("&");
//处理'POST'和'GET'两种方式提交的差异
if(opt.method.toUpperCase() === "POST"){
xmlHttp.open(opt.method,opt.url,opt.async);
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
}else if(opt.method.toUpperCase() === "GET"){
xmlHttp.open(opt.method,opt.url+"?"+ postData + new Date().getTime(),opt.async);
xmlHttp.send(null);
}
//返回的数据状态正确,则给opt.success()传回数据
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
opt.success(xmlHttp.responseText);
}
}
}