XMLHttpRequest基础|封装函数
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>XMLHttpRequest</title>
</head>
<body>
<h1>XMLHttpRequest</h1>
<a href="#" id="btn">异步加载</a>
<script>
var btn = document.getElementById("btn");
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/*
传统写法 start*/
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//对XMLHttpRequest封装成方法
/*

function createXHR(){
return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
}
*/
btn.onclick
= function(){
/*
var xhr = createXHR();
url = "test.php?"+(+new Date());
//xhr.open("get",url);
xhr.open("post",url);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("ps=true&username=xylxq1925&pwd=xylxq3270918");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
//alert(xhr.responseText);
var xml = xhr.responseXML;
alert(xml.documentElement.firstChild.nodeValue);
}
}
//alert(xhr.responseText);
*/
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/*
传统写法 end*/
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<



//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/*
把上面所有功能整合成一个函数 start*/
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
function createXHR(){
return window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject();
}

/*
*args参数是一个对象
*属性: method,url,
dada: HashMap {key:value}
*方法:success: Function
*/
function ajax(args){
var xhr = createXHR();
var data =params(args.data);
args.method
= args.method || "get";
if(args.method == "post"){
xhr.open(args.method,args.url,
true);
}
xhr.open(args.method,args.url
+"?"+data);

if(args.method == "post"){
xhr.setRequestHeader(
"Content-Type","application/x-www-form-urlencoded");
xhr.send(data);
}
else{
xhr.send();
}
xhr.onreadystatechange
= function(){
if(xhr.status===200 && xhr.readyState===4){
args.success(xhr.responseText,xhr.resposeXML);
}
}

function params(obj){
var a = [];
for(i in obj){
a.push(encodeURIComponent(i)
+"="+ encodeURIComponent(obj[i]));
}
return a.join("&");
}
}


//方法的调用
ajax({
method:
"post",
url:
"test.php",
data:{
"key":"value","username":"xylxq"},
success:
function(text){
alert(text);
}
});
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/*
把上面所有功能整合成一个函数 end*/
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
</script>
</body>
</html>

//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
/*
下面是请求的服务器端语言 文件名test.php*/
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<?php
file_put_contents(
"test.txt",date("H:i:s"));
//echo date("中文");
header("content-type:text/xml");
echo
"<?xml version='1.0' encoding='utf-8'?>
<root>
 XML文件
</root>
";
?>

 

posted on 2010-12-12 11:21  xylxq1925  阅读(111)  评论(0编辑  收藏  举报