js 原生ajax:封装函数
2017-05-19 09:47
127 查看
1、打开服务器WampServer;
2、将文件放置在WampServer的www文件夹下;
3、打开时网页地址栏为localhost+www下的地址。eg:http://localhost/myworld/5.19ajax/index.html?__hbt=1495158145298
4、调用方式:
函数为:
2、将文件放置在WampServer的www文件夹下;
3、打开时网页地址栏为localhost+www下的地址。eg:http://localhost/myworld/5.19ajax/index.html?__hbt=1495158145298
4、调用方式:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input type="button" id="btn" value="提交"/> <span id="info"></span> </body> <script src="js/ajax_util.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> var btn=document.getElementById('btn'); var info=document.getElementById('info'); btn.onclick=function(){ //date为空,无数据传送; ajax('GET','/myworld/5.19ajax/span.txt','',function(str){ info.innerHTML=str; }) } </script> </html>
函数为:
/* * ajax 4条线 * 第3条线由后台完成,直接调用 */ function ajax(method,url,data,fn){ //1 var xhr; if (window.XMLHttpRequest) { xhr=new XMLHttpRequest(); }else{ xhr=new ActiveXObject('Microsoft XMLHTTP'); }; //2 if (method=='GET'&&data) { url=url+'?'+data; }; xhr.open(method,url,true); if(method=='GET'){ xhr.send(null); }else{ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(data); }; //4 xhr.onreadystatechange=function(){ if (xhr.readyState==4) { if (xhr.status==200) { if (xhr.responseXML) { fn(xhr.responseXML); }else{ fn(xhr.responseText); }; }else{ console.log('出错状态为:'+xhr.status); }; } }; };
相关文章推荐
- 原生JS ajax 判定浏览器是否关闭
- 使用原生JS封装Ajax
- js原生Ajax的封装与使用
- 原生js,jquery通过ajax获得后台json数据动态新增页面元素
- 原生js实现ajax用于简单的签到或登录
- 原生js方式实现ajax,并仿jquery方式简单调用
- 原生Ajax至mini-ajax.js
- 用原生js,json解析ajax传回来的数据
- AJAX学习笔记之XML对象原生JS使用方法
- js原生ajax
- 原生JS Ajax 提交post表单信息
- 通过原生js的ajax或jquery的ajax获取服务器的时间
- 【Javascript】原生js实现ajax功能
- ajax和原生js比较与理解
- Ajax原理及用原生js实现Ajax应用
- 习惯了使用jQuery的ajax方法,看看原生js使用xmlhttpRequest实现ajax请求
- 原生js的ajax与sturts2实例
- 使用原生JS编写ajax操作XMLHttpRequst对象
- js 原生 ajax 异步上传图片
- [代码]JS原生Ajax,GET和POST