1、JavaScript代码

//封装ajax
function ajax(obj) {
var xhr = new createXHR();
obj.url = obj.url + '?rand=' + Math.random();
obj.data = params(obj.data);
if (obj.method === 'get') {
obj.url = obj.url.indexOf('?') == -1 ? obj.url + '?' + obj.data : obj.url + '&' + obj.data;
}
if (obj.async === true) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
callback();
}
}
}
xhr.open(obj.method, obj.url, obj.async);
if (obj.method === 'post') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(obj.data);
} else {
xhr.send(null);
}
if (obj.async === false) {
callback();
}

function callback () {
if (xhr.status == 200) {
obj.success(xhr.responseText); //回调
} else {
alert('数据返回失败!状态代码:' + xhr.status + ', 状态信息:' + xhr.statusText);
}
}
}

//调用ajax
addEvent(document, 'click', function () { //IE6 需要重写addEvent
ajax({
method : 'post',
url : 'ajax.php',
data : {
'name' : 'Lee',
'age' : 100
},
success : function (text) {
alert(text);
},
async : true
});
});

//名值对编码
function params(data) {
var arr = [];
for (var i in data) {
arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i]));
}
return arr.join('&');
}

//点击事件
function addEvent(obj,eventType,fn){
if(obj.addEventListener){
obj.addEventListener(eventType,fn,false);
}else if(obj.attachEvent){
obj.attachEvent('on'+eventType,fn);
}else{
obj['on'+eventType] = fn;
}
};

//XHR对象
function createXHR(){
//检测原生XHR对象是否存在,如果存在刚返回它的新实例;
//如果不存在,则检测ActiveX对象;
//如果两个都不存在,就抛出一个错误。

if(typeof XMLHttpRequest != "undefined"){
return new XMLHttpRequest();
}else if(typeof ActiveXObject != "undefined"){
//适合IE7之前的版本
if(typeof arguments.callee.activeXString != "string"){
var versions = ["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML.XMLHttp"];
for(var i=0,len=versions.length; i<len; i++){
try{
var xhr = new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
return xhr;
}catch (ex){
//跳过
}
}
}

return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("No XHR object available.");
};
}

2、HTML代码

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ajax</title>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>ajax</body>
</html>

3、PHP代码

<?php
print($_GET);
print($_POST);
?>

posted on 2016-08-24 17:40  df-xfz  阅读(426)  评论(0编辑  收藏  举报