温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-07-15 09:29:20 来源:亿速云 阅读:107 作者:chen 栏目:web开发

这篇文章主要介绍“Ajax对象包含post和get两种异步传输方式实例”,在日常操作中,相信很多人在Ajax对象包含post和get两种异步传输方式实例问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”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对象包含post和get两种异步传输方式实例”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI