1.跨域体验
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="./libs/jquery/jquery.js"></script>
</head>
<body>
<button>发起跨域请求</button>
<script>
$('button').on('click', function() {
$.ajax({
url: 'http://127.0.0.1:3001/getStudentsJSONP.js',
dataType: 'jsonp',
success: function(res) {
console.log(res)
}
})
})
</script>
</body>
</html>
2.jsonp跨域的原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<script src="./libs/jquery/jquery.js"></script>
<link
rel="stylesheet"
href="https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superui/css/ubase_9376fdcf.css"
/>
</head>
<body>
<button>发起跨域请求</button>
<script>
function test(res) {
console.log(res)
}
</script>
<script src="http://127.0.0.1:3001/getStudentsJSONP.js?callback=test">
</script>
</body>
</html>
3.jsonp的原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script>
function abc(res) {
console.log(res)
}
</script>
<script>
let $ = {
ajax: function(option) {
if (option.dataType === 'jsonp') {
let script = document.createElement('script')
script.src = option.url + '?callback=abc'
document.body.appendChild(script)
} else {
let xhr = new XMLHttpRequest()
}
}
}
$.ajax({
url: 'http://127.0.0.1:3002/getdata',
dataType: 'jsonp'
})
</script>
</body>
</html>