使用script標籤是如何實現跨域請求的,它是一個新技術,仍是一個技巧? 下面咱們來看看,其中簡單的原理:html
咱們寫一個很日常的example.js,文件內容展現以下:前端
getJson({
results: [
{
name: 'xxx',
code: 1
}
]
});
複製代碼
接下來,再寫一個簡單的index.html文件:node
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jsonp</title>
<script>
function getJson(data) {
console.log(data);
}
</script>
<script src="http://127.0.0.1:3000/example.js"></script>
</head>
<body></body>
</html>
複製代碼
上面的index.html代碼,當成功的請求到example.js後,至關於這樣:express
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jsonp</title>
<script>
function getJson(data) {
console.log(data);
}
</script>
<script>
// 這裏是:src="http://127.0.0.1:3000/example.js"請求成功後,返回的代碼(數據)
getJson({
results: [
{
name: 'xxx',
code: 1
}
]
});
</script>
</head>
<body></body>
</html>
複製代碼
相信寫到這裏,是能看得明白的,下面正式開始說JSONP的實現,我用的是nodejs後臺:json
前端代碼index.html,給"http://http://127.0.0.1:3000/example.js"請求地址加一個get請求參數?callback=getJson,代碼示例以下:後端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jsonp</title>
<script>
function getJson(data) {
console.log(data);
}
</script>
<script src="http://127.0.0.1:3000/example.js?callback=getJson"></script>
</head>
<body></body>
</html>
複製代碼
後端server.js代碼以下:跨域
const express = require('express');
const server = express();
server.use('/example.js', (req, res) => {
// req.query.callback是getJson
let methodName = req.query.callback;
let data = {
results: [
{
name: 'xxx',
code: 1
}
]
};
let dataStr = JSON.stringify(data),
// 至關於sendStr = `getJson(${dataStr})`
sendStr = `${methodName}(${dataStr})`;
res.send(sendStr);
});
server.listen(3000);
console.log('server running at 127.0.0.1:3000');
複製代碼
當請求成功後,index.html代碼解析以下:bash
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jsonp</title>
<script>
function getJson(data) {
console.log(data);
}
</script>
<script>
// 這裏是:src="http://127.0.0.1:3000/example.js?callback=getJson"請求成功後,返回的代碼(數據)
getJson('{"results":[{"name":"xxx","code":1}]}')
</script>
</head>
<body></body>
</html>
複製代碼
最後聲明,爲了方便你們理解,我把請求寫成了一個example.js,其實接口只要一個字符串就能夠了,例如"http://127.0.0.1:3000/example?callback=getJson",其中.js文件格式,徹底是爲了幫助你們理解。jsonp