Created
February 1, 2019 09:14
-
-
Save ClausClaus/f487a6a0f290c2d8c4a7ab12c1686748 to your computer and use it in GitHub Desktop.
jsonp example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<title>jsonp请求测试</title> | |
</head> | |
<body> | |
<script> | |
function jsonp({ url, params, callback }) { | |
return new Promise((resolve, reject) => { | |
let script = document.createElement('script') | |
window[callback] = function(data) { | |
resolve(data) | |
document.body.removeChild(script) | |
} | |
params = { ...params, callback } // wd=b&callback=show | |
let arrs = [] | |
for (let key in params) { | |
arrs.push(`${key}=${params[key]}`) | |
} | |
script.src = `${url}?${arrs.join('&')}` | |
document.body.appendChild(script) | |
}) | |
} | |
jsonp({ | |
url: 'http://localhost:3000/say', | |
params: { wd: 'Iloveyou' }, | |
callback: 'show' | |
}).then(data => { | |
console.log(data) | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let express = require('express') | |
let app = express() | |
app.get('/say', function(req, res) { | |
let { wd, callback } = req.query | |
console.log(wd) // Iloveyou | |
console.log(callback) // show | |
res.end(`${callback}('我不爱你')`) | |
}) | |
app.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment