用户登录
用户注册

分享至

Ajax 对象 包含post和get两种异步传输方式

  • 作者: 我们是哥们丶
  • 来源: 51数据库
  • 2021-09-04
复制代码 代码如下:

/**
* @author supersha
* @qq:770104121
*/
<!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>ajax document</title>
<script type="text/javascript">
//注意,编码要同意为utf-8才能避免中文参数和返回中文的乱码问题
function ajax(prop){
this.action(prop); //在实例化的时候就调用action方法
}
ajax.prototype = {
createxhr: function(){ //创建xmlhttprequest对象
var xhr = false;
if (window.xmlhttprequest) {
xhr = new xmlhttprequest();
}
else
if (window.activexobject) {
try {
xhr = new activexobject("msxml2.xmlhttp");
}
catch (e) {
xhr = new activexobject("microsoft.xmlhttp");
}
}
return xhr;
},
action: function(prop){
var xhr = this.createxhr();
if (xhr) {
var url = encodeuri(prop["url"]); //对url进行编码
if (prop["method"] == "get" && url && prop["success"]) { //get方法
xhr.onreadystatechange = function(){
(function(){ //自执行函数用于检查服务器的返回状态并执行回调函数
if (xhr.readystate == 4 && xhr.status == 200) {
prop["success"](xhr); //执行回调函数
}
})();
};
//alert(prop["hander"] instanceof function);
xhr.open("get", url, true);
xhr.send(null);
}
else
if (prop["method"] == "post" && url && prop["success"]) { //post方法
xhr.onreadystatechange = function(){
(function(){
if (xhr.readystate == 4 && xhr.status == 200) {
prop["success"](xhr); //执行回调函数
}
})();
};
if (prop["params"]) {
url = url.indexof("?") > -1 ? url + "&" + prop["params"] : url +"?" + prop["params"];
}
xhr.open("post", url, true);
xhr.setrequestheader("content-type", "application/x-www-form-urlencoded");
xhr.send(null);
}
}
else
if (!xhr && prop["fail"]) {
prop["fail"]();
}
}
}
function getdata(){
var ajax = new ajax({
url: "test.php",
method: "post",
success: oncomplete,
params: "name="+escape("沙锋") //进行编码
});
}
function oncomplete(obj){
alert(unescape(obj.responsetext)); //进行转码
}
</script>
</head>
<body>
<input type="button" value="get data" onclick="getdata()"/>
</body>
</html>

注释:
ajax对象接受一个对象字面量为参数,这个对象字面量中包含method,url,success,params,fail参数
method:"get"或者"post"
url:服务器端文件路径
success:当请求没有错误的时候,调用的回调函数,该回调函数带一个xmlhttprequest对象的参数
fail:当请求错误的时候调用
params:当使用post方法发送请求是,params为参数字符串
软件
前端设计
程序设计
Java相关