标签:
一直用 都是jquery和angular的ajax库,也没看过源码,真是惭愧,一知半解,通过学习了解下
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="智能社 - zhinengshe.com" /> <meta name="copyright" content="智能社 - zhinengshe.com" /> <title>智能社 - www.zhinengshe.com</title> <script src="myAjax5.js"></script> <script> window.onload = function(){ var oBtn = document.getElementById("btn1"); oBtn.onclick = function(){ $.ajax({ url:"post.php", data:{ a:22, b:22 }, type:"get", timeout:-1, success:function(str){ alert(str); }, error:function(){ alert("失败"); } }); }; }; </script> </head> <body> <input id="btn1" type="button" value="按钮"/> </body> </html>
<?php $a = $_GET["a"]; $b = $_GET["b"]; echo $a + $b; ?>
//版权 北京智能社©, 保留所有权利 var $ = {}; $.ajax = ajax; function json2url(json){ var arr = []; json.t = Math.random(); for(var name in json){ arr.push(name + "=" + encodeURIComponent(json[name])); } return arr.join("&"); } //options url,data,type,timeout,success,error function ajax(options){ options = options || {}; if(!options.url){ alert("请输入url,别太懒了!"); return ; } options.data = options.data || {}; options.type = options.type || "get"; options.timeout = options.timeout || 0; var str = json2url(options.data); //1 创建 if(window.XMLHttpRequest){ var xhr = new XMLHttpRequest(); } else { var xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(options.type == "get"){ //2 连接 xhr.open("get",options.url +"?"+str,true); //3 发送请求 xhr.send(); } else { //2 连接 xhr.open("post",options.url,true); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3 发送请求 xhr.send(str); } //4 接收数据 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){//完成 clearTimeout(timer); if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ options.success && options.success(xhr.responseText); } else { options.error && options.error(xhr.status); } } }; if(options.timeout){ var timer = setTimeout(function(){ xhr.abort(); },options.timeout) } }
标签:
原文地址:http://www.cnblogs.com/heboliufengjie/p/4725359.html