使用script標(biāo)簽是如何實(shí)現(xiàn)跨域請求的,它是一個(gè)新技術(shù)削祈,還是一個(gè)技巧?
下面我們來看看削饵,其中簡單的原理:
我們寫一個(gè)很平常的example.js岩瘦,文件內(nèi)容展示如下:
getJson({
results: [
{
name: 'xxx',
code: 1
}
]
});
接下來,再寫一個(gè)簡單的index.html文件:
<!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代碼窿撬,當(dāng)成功的請求到example.js后启昧,相當(dāng)于這樣:
<!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"請求成功后,返回的代碼(數(shù)據(jù))
getJson({
results: [
{
name: 'xxx',
code: 1
}
]
});
</script>
</head>
<body></body>
</html>
相信寫到這里劈伴,是能看得明白的密末,下面正式開始說JSONP的實(shí)現(xiàn),我用的是nodejs后臺:
前端代碼index.html跛璧,給"http://http://127.0.0.1:3000/example.js"請求地址加一個(gè)get請求參數(shù)?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),
// 相當(dāng)于sendStr = `getJson(${dataStr})`
sendStr = `${methodName}(${dataStr})`;
res.send(sendStr);
});
server.listen(3000);
console.log('server running at 127.0.0.1:3000');
當(dāng)<script src="http://127.0.0.1:3000/example.js?callback=getJson"></script>請求成功后,index.html代碼解析如下:
<!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"請求成功后追城,返回的代碼(數(shù)據(jù))
getJson('{"results":[{"name":"xxx","code":1}]}')
</script>
</head>
<body></body>
</html>
最后聲明刹碾,為了方便大家理解,我把請求寫成了一個(gè)example.js座柱,其實(shí)接口只要一個(gè)字符串就可以了,例如"http://127.0.0.1:3000/example?callback=getJson"迷帜,其中.js文件格式,完全是為了幫助大家理解色洞。