javascript - 封装jsonp
2024-09-04 18:04:49
jsonp牵扯到同源策略、跨域等问题,这里不细说了.
实现就是创建动态的script标签来请求后台地址:
示例:
jsonp('xxx.php', { uid: 1 }, function (res) {
console.log(res)
})
实例:
jsonp('http://localhost/server.php', { uid: 1 }, function (res) {
console.log(res)
})
function jsonp (url, params, callback) {
var funcName = 'jsonp' + Date.now() + Math.random().toString().substr(2, 5) if (typeof params === 'object') {
var tempArr = []
for (var key in params) {
var value = params[key]
tempArr.push(key + '=' + value)
}
params = tempArr.join('&')
} var script = document.createElement('script')
script.src = url + '?' + params + '&callback=' + funcName
document.body.appendChild(script) window[funcName] = function (data) {
callback(data)
delete window[funcName]
document.body.removeChild(script)
}
}
最新文章
- MySQL的InnoDB索引原理详解
- Spring--开山篇
- Oracle SQL的硬解析和软解析
- js profiler
- python多进程共享变量Value使用tips
- C标准函数库(常用部分)
- CSS居中完全解决方案
- oj 1031 random permutation
- Magento路径函数getBaseUrl使用方法
- C语言redirection
- jquery live()只支持css选择器
- 使用Linux的命令行工具做简单的文本分析
- 实现类似QQ的折叠效果
- cocos2dx进阶学习之CCTMXLayer
- C语言获取文件SHA1哈希
- FS SIP呼叫的消息线程和状态机线程
- 一些css3的特效 javascript的window对象 定时器 延时器等ing...
- APNs 推送原理及问题
- node-express-1
- Linux命令:popd
热门文章
- tips 前端 背景与元素的透明和模糊
- weblogic12c配置免密码启动
- webdriver操作iframe标记的编辑器
- ReferenceError与undefined的区别
- (转)cygwin包管理器apt-cyg
- Centos 查看内存
- python的加密操作
- This template requires a more recent version of the Android Eclipse plugin. Please update from versi
- Table is marked as crashed and should be repaire (
- centos 部署web项目