关键点:
1.利用script标签的src请求数据,且浏览器不进行同源限制
2.与服务器约定好callback,服务器返回的是一段js;在window里面定义全局callback函数,执行回调函数。
3.缺点:只能进行get请求
源码:
<script type="text/javascript">
function createScript(url, charset) {
var script = document.createElement('script')
script.setAttribute('src', url)
script.setAttribute('type', 'text/javascript')
charset && script.setAttribute('charset', charset)
script.async = true
return script
}
function getJsonp(url, success, error, charset) {
var url = url += '&callback'
var script = createScript(url, charset)
window.Jsonp1 = function () {
if (success && typeof success === 'function') {
success(arguments[0])
}
}
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded | complete/.test(script.readyState)) {
script.onload = script.onreadystatechange = null
if (script.parentNode) {
script.parentNode.removeChild(script)
}
}
window.Jsonp1 = null
}
script.onerror = function () {
error()
}
document.getElementsByTagName('head')[0].appendChild(script)
}
getJsonp('http://127.0.0.1:8887/?jsonp', function (data) {
var data = JSON.parse(data)
console.log("Jsonp1.data", data.name)
}, function () {
console.log("jsonp 请求失败")
}, 'UTF-8')
</script>