手机
当前位置:查字典教程网 >编程开发 >AJAX相关 >Ajax 对象 包含post和get两种异步传输方式
Ajax 对象 包含post和get两种异步传输方式
摘要:复制代码代码如下:/***@authorSupersha*@QQ:770104121*/AjaxDocument//注意,编码要同意为utf...

复制代码 代码如下:

/**

* @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"/>

</body>

</html>

注释:

Ajax对象接受一个对象字面量为参数,这个对象字面量中包含method,url,success,params,fail参数

method:"GET"或者"POST"

url:服务器端文件路径

success:当请求没有错误的时候,调用的回调函数,该回调函数带一个XMLHttpRequest对象的参数

fail:当请求错误的时候调用

params:当使用POST方法发送请求是,params为参数字符串

【Ajax 对象 包含post和get两种异步传输方式】相关文章:

ajax中data传参的两种方式分析

创建ajax对象并兼容多个浏览器

Ajax+js实现异步交互

jQuery Ajax 实例详解 ($.ajax、$.post、$.get)

ajax异步请求刷新

Ajax中的循环方案

Ajax点击不断加载数据列表

ajax同步异步简单实现

AJAX 异步传输数据的问题

Ajax实现异步用户名验证功能

精品推荐
分类导航