<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
</body>
<script src="./index.js"></script>
<script>
//调用
Ajax({
url:'./index.php',
type:'GET',
data:{ name:'wdk',age:23 },
dataType:'text', //预期服务器返回类型 xml , text, json
async:true, //异步请求
timeout:5000, //请求超时
beforeSend:function(){
//console.log('beforeSend');
},
complete:function(){
//console.log('complete');
},
success:function(res){
console.info('success',res);
},
error:function(){
console.error('error');
}
})
</script>
</html>
Javascript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Ajax = factory());
})( this, (function () {
'use strict';
/**
* [extend]
* @param {[Object]} chd [children]
* @param {[Object]} far [parent]
* @return {[Object]}
*/
function extend(chd,far){
for(var x in far){
far[x] && (chd[x]=far[x]);
}
}
/**
* [O_to_S change object to string]
* @param {[Object]} obj
* @return {String}
*/
function O_to_S(obj,post){
var result='',reg=/^\?/,reg2=/^\&/;
for(var x in obj){
if (!post) {
if (!reg.test(result)) {
result+='?'+x+'='+obj[x];
}else{
result+='&'+x+'='+obj[x];
}
}else{
if (!reg2.test(result)) {
result+=x+'='+obj[x]+'&';
}else{
result+=x+'='+obj[x];
}
}
}
return result;
}
function Ajax(ops){
var def={
url:'',
type:'GET',
data:null,
dataType:'json',
async:true,
timeout:5000,
beforeSend:null,
complete:null,
success:null,
error:null
};
extend(def,ops);
if (def.url==='') {alert('Request address is empty!');return;}
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.timeout=def.timeout;//请求超时
xhr.ontimeout=function(){
alert('request timeout!');
};
xhr.onloadstart=def.beforeSend;//请求开始
if (def.type.toUpperCase()==='GET') {
var dataString=O_to_S(def.data);
if ( dataString !== '') {
def.url += dataString;
}
}
xhr.onreadystatechange = function(){
if (xhr.readyState === 4) {
def.complete();//请求完成
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
var options_type=def.dataType.toLowerCase(),xhrdata;
if (options_type === 'xml') {
xhrdata = xhr.responseXML;
}else if(options_type === 'json'){
xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')');
}else{
xhrdata = xhr.responseText;
}
def.success(xhrdata);//请求成功
} else {
def.error && def.error();
//console.log(xhr.status, xhr.statusText);
}
}
};
xhr.open( def.type.toUpperCase() , def.url , def.async );
if (def.type.toUpperCase()==='POST') {
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');//请求头很重要 xhr.open后添加
xhr.send( O_to_S(def.data,true) );
}else{
xhr.send();
}
//console.log(O_to_S(def.data,true))
}
return Ajax;
}))
PHP
<?php
if ( isset($_GET["name"]) ) {
echo $_GET["name"];
}
if ( isset($_POST["name"]) ) {
echo $_POST["name"];
}
?>
网友评论