关于JSONP
来源:互联网 发布:apche怎么使用php 编辑:程序博客网 时间:2024/05/21 22:54
借助 script 标签去发送http请求:JSONP
用jsonp去完成一个简单的跨域请求
1、没有改变CORS的页面不能随便跨域
2、为了保证同源策略,ajax也不能跨域请求
3、老一点的浏览器还不支持CORS
要注意的就是所请求的服务器一定要是可信任的服务器,防止别人“接管”你的网站
JSONP有别于JSON ,多了那个P是 “前缀”或者“填充”的意思,{“name”:”steven”,”age”:12} =>callback({“name”:”steven”,”age”:12} );
这里就完成了一个JSONP的小demo
function handleResponse(res){ alert(res.city); } var script = document.createElement("script"); script.src = "http://freegeoip.net/json?callback=handleResponse"; document.body.appendChild(script);
下面的英文写的有点坑(借用了犀牛的代码)
/** * @param {string} url * @param {Function} callback 回掉函数 * @return {[type]} */ function getJSONP(url,callback){ // create callback function `s name var cbnum = 'cb' + getJSONP.counter++; var cbname = 'getJSONP.' + cbnum; // use code to decoration function name and add too url `s search // use jsonp as param name some support json server // maybe otherelse param like callback if(url.indexOf('?') === -1){ url += "?callback=" + cbname; // as url search }else{ url += "&callback=" + cbname; // as url param } // create script element to send request var script = document.createElement('script'); // define perform function getJSONP[cbnum] = function(response){ try{ callback(response); // deal response } finally{ delete getJSONP[cbnum]; //delete this function script.parentNode.removeChild(script); // delete this script node } }; // trigger http request script.src = url; document.body.appendChild(script); // add script element to document } getJSONP.counter = 0;
0 0
- 关于JSONP
- 关于jsonp
- 关于JSONP
- 关于JSONP
- 关于JSONP的理解
- 关于jsonp的理解
- 关于jsonp的理解
- 一篇关于什么是jsonp
- 关于JSONP的理解
- 关于jsonp跨域
- jsonp 关于跨域
- 关于JSONP的问题
- 关于json、jsonp
- 关于JSON和JSONP
- 关于json和jsonp
- 关于jsonp使用
- jQuery---关于JSON和JSONP
- 关于jsonp访问天气预报功能
- Python下Flask-ApScheduler快速指南
- Angular4学习笔记(六):解耦
- Python下APScheduler的快速指南
- struts2 中ActionContext.getContext().getSession().put("","")是什么意思 和HttpSession有什么区别吗?
- C. Voltage Keepsake
- 关于JSONP
- Go语言学习之log包(The way to go)
- 实现一个java web缓存
- Fragment带参数启动的坑
- 浅析智能指针
- android developer tiny share-201704017
- [LeetCode]168. Excel Sheet Column Title(Excel表格列标题)
- 滴滴2016校招测评题(建水库问题)
- c 求字符串内无重复字符的最长子串