当前位置: 网学 > 编程文档 > Ajax > 正文

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

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: 用户投稿 来源: 网络 发布时间: 13/07/12

网学网Ajax编辑为广大网友搜集整理了:Ajax 对象 包含post和get两种异步传输方式绩等信息,祝愿广大网友取得需要的信息,参考学习

复制代码 代码如下:
/**
* @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为参数字符串
  • 上一篇资讯: 自己动手封装的 ajax
  • 下一篇资讯: Ajax 超时检查脚本
  • 网学推荐

    免费论文

    原创论文

    设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
    版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
    Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved 湘ICP备09003080号