function ajax(options){
// 格式化参数
var params = formData( options.data );
// 创建ajax对象
var xhr = null;
if( window.XMLHttpRequest ){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 连接服务器并发送请求
if( options.type = "GET" ){
xhr.open( options.type, options.url+"?"+params, options.async );
xhr.send(null);
}else if( options.type = "POST" ){
xhr.open( options.type, options.url, options.async );
xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" );
xhr.send(params);
}
// 接受返回值,数据处理和展示
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 && xhr.status == 200 ){
options.success( xhr.responseText );
}
}
// function--格式化参数
function formData(obj){
var arr = [];
for( var i in obj ){
arr.push( i + "=" + obj[i] );
}
return arr.join( "&" );
}
}
// 调用
ajax({
url: "a.php",
type: "GET",
async: true,
data: {name: "Jenny", age: 18},
success: function(data){
console.log( data );
}
})
a.php:
<?php
echo $_GET["name"]."===>".$_GET["age"];
?>
输出结果:
Jenny===>18