ajax原生js面向对象封装及开发时遇到的问题
来源:互联网 发布:淘宝网店开店流程 编辑:程序博客网 时间:2024/06/06 02:04
在工作中我们经常会向后台请求各种数据,遇到各种问题,以自己在该开始开发时经常出现的错误来说明。
1、首先定义一个对象 Ajax
var Ajax = { ajax : function(type,url,callback){ var xhr = new XMLHttpRequest();//定义对象 xhr.open(type , url , true); if(type == 'post'){ xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8'); xhr.send(); }else{ xhr.send(); } xhr.onreadystatechange = function () { if( xhr.readyState === 4 && xhr.status ===200){ console.log(xhr.responseText) console.log(JSON.parse(xhr.responseText)); callback && callback(); } } }}
上面是封装好的Ajax对象,在调用时只需要进行下面操作
window.onload = function (){ Ajax.ajax('type' ,'自己数据的路径' , function (){//进行数据的处理 console.log(this);//查看此时的对象是谁 console.log(arguments);//实参列表 } )}
出现下面图片中的问题是如何出现的:
(1)没有开启服务器,或者没有再服务器端打开文件,只是本地打开
(2)有可能是服务器端口冲突,没有达到同源策略。
2、在ajax请求时需要给路径后面链接一些参数,然后去请求数据(以post为例封装)
function Post(opt) { this.init(opt);}Post.prototype = { constructor: 'Post', init: function (opt) { this.method = 'POST'; this.data = opt.data || null; this.url = opt.url || ''; this.async = true; this.success = opt.success || function () {} this.format(); }, format: function () {//将data中的键值对用变成“键=值&键=值” var data = this.data; var params = []; for (var key in data) { params.push(key + '=' + data[key]); } this.postData = params.join('&'); this.xhr(); }, xhr: function () { var that = this; var xhr = new XMLHttpRequest();//定义一个对象 xhr.open(this.method, this.url, this.async); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=utf-8'); xhr.send(this.postData);//发送 xhr.onreadystatechange = function () { if (xhr.status === 200 && xhr.readyState === 4) { that.success(xhr.response); } } }}
然后调用此函数,demo如下:
new Post({ url:'http://www.tuling123.com/openapi/api', data:{ "键":"值", "键":"值" }, success:function(res){ console.log(res) console.log(this) console.log(argunents) } })
阅读全文
1 0
- ajax原生js面向对象封装及开发时遇到的问题
- 原生js封装Ajax
- 原生js封装ajax
- 原生JS封装Ajax
- 原生JS封装ajax()
- js 实现对ajax请求面向对象的封装
- 原生JS封装的ajax请求
- js面向对象的封装
- 原生js面向对象
- 原生JS面向对象
- 原生JS面向对象
- 原生JS面向对象
- 将ajax请求封装为一个对象(原生js)
- 原生js的面向对象相关
- 封装的原生ajax
- 原生ajax的封装
- 原生js封装ajax方法
- 原生JS封装AJAX请求
- LeetCode编程练习
- STL-deque容器
- LeetCode编程练习
- Django的项目的重新部署
- kali 源
- ajax原生js面向对象封装及开发时遇到的问题
- LeetCode编程练习
- hadoop2.7伪分布安装配置
- LeetCode编程练习
- 谷歌扩展程序开发常用工具(Develop Tools)
- LeetCode编程练习
- antrl4学习(三)——用idea实现简单计算器
- LeetCode编程练习
- C++开发uwp的坑