-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
day-15-实现一个jsonp #15
Comments
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<script>
// 转换成链接参数形式
let parseParam = function (param, key) {
var paramStr = ""
if (param instanceof String || param instanceof Number || param instanceof Boolean) {
paramStr += "&" + key + "=" + encodeURIComponent(param)
} else {
$.each(param, function (i) {
var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i)
paramStr += '&' + parseParam(this, k)
})
}
return paramStr.substr(1)
}
function jsonp(url, data = {}, callback) {
return new Promise(function (resolve, reject) {
let reqUrl;
data[callback] = callback
// 对象序列化并和url拼接
reqUrl = url + '?' + parseParam(data)
let script = document.createElement("script")
script.src = reqUrl
$('body').append(script)
if (window[callback]) {
} else {
window[callback] = function (data) {
resolve(data)
}
}
})
}
// ?jsoncallback=fn&page=1&cate=recommend
jsonp('http://photo.sina.cn/aj/index',
{
page: 1, cate: 'recommend'
}, 'jsoncallback')
.then(data => {
console.log(data)
})
jsonp('http://photo.sina.cn/aj/index',
{
page: 2, cate: 'recommend'
}, 'jsoncallback')
.then(data => {
console.log(data)
})
</script>
</body>
</html> |
js部分 let parseParam = function (param, key) {
var paramStr = ""
if (param instanceof String || param instanceof Number || param instanceof Boolean) {
paramStr += "&" + key + "=" + encodeURIComponent(param)
} else {
$.each(param, function (i) {
var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i)
paramStr += '&' + parseParam(this, k)
})
}
return paramStr.substr(1)
}
function jsonp(url, data = {}, callback) {
return new Promise(function (resolve, reject) {
let reqUrl;
data[callback] = callback
// 对象序列化并和url拼接
reqUrl = url + '?' + parseParam(data)
let script = document.createElement("script")
script.src = reqUrl
$('body').append(script)
if (window[callback]) {
} else {
window[callback] = function (data) {
resolve(data)
}
}
})
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
封装一个
jsonp
方法,可以使用如下方式调用The text was updated successfully, but these errors were encountered: