JavaScript 自定义封装XMLHttpRequest

来源:互联网 发布:硕士毕业论文 知乎 编辑:程序博客网 时间:2024/05/23 22:44
ajaxGet("http://localhost/shop/shopPHP/?c=User&f=getUser&userId=1",function (res) {console.log(res)})function ajaxGet(url,fn) {let xhr=new XMLHttpRequest();xhr.open("GET",url);xhr.send();xhr.onreadystatechange=function () {if (xhr.readyState==4&&xhr.status==200) {fn(xhr.responseText);}}}let params={"c":"User","f":"getUser","userId":"1"};ajaxPost("http://localhost/shop/shopPHP/",params,function (res) {console.log(res)})function ajaxPost (url,obj,fn) {let xhr=new XMLHttpRequest();xhr.open("POST",url);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");for (key in obj) {params+="&"+key+"="+obj[key]}xhr.send(params);xhr.onreadystatechange=function () {if (xhr.readyState==4&&xhr.status==200) {fn(xhr.responseText);}}}


原创粉丝点击