|
導(dǎo)讀網(wǎng)頁(yè)的本質(zhì)就是超級(jí)文本標(biāo)記語(yǔ)言,通過(guò)結(jié)合使用其他的Web技術(shù)(如:腳本語(yǔ)言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁(yè)。因而,超級(jí)文本標(biāo)記語(yǔ)言是萬(wàn)維網(wǎng)(Web)編程的基礎(chǔ),也就是說(shuō)萬(wàn)維網(wǎng)是建立... 網(wǎng)頁(yè)的本質(zhì)就是超級(jí)文本標(biāo)記語(yǔ)言,通過(guò)結(jié)合使用其他的Web技術(shù)(如:腳本語(yǔ)言、公共網(wǎng)關(guān)接口、組件等),可以創(chuàng)造出功能強(qiáng)大的網(wǎng)頁(yè)。因而,超級(jí)文本標(biāo)記語(yǔ)言是萬(wàn)維網(wǎng)(Web)編程的基礎(chǔ),也就是說(shuō)萬(wàn)維網(wǎng)是建立在超文本基礎(chǔ)之上的。超級(jí)文本標(biāo)記語(yǔ)言之所以稱(chēng)為超文本標(biāo)記語(yǔ)言,是因?yàn)槲谋局邪怂^“超級(jí)鏈接”點(diǎn)。 本篇文章給大家?guī)?lái)的內(nèi)容是關(guān)于JSONP跨域請(qǐng)求的理解(代碼示例),有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。對(duì)于JSONP一直是知半解,今天利用周末整理了一下 維基百科的解釋?zhuān)?/p> JSONP (JSON with Padding or JSON-P[1]) is a javascript pattern to request data by loading a <script> tag. It was proposed by Bob Ippolito in 2005.[2] JSONP enables sharing of data bypassing same-origin policy. The policy disallows running JavaScript to read media DOM elements or XHR data fetched from outside the page's origin. The aggregation of the site's scheme, port number and host name identifies as its origin. 我的理解是: 1、前端編寫(xiě)自己的函數(shù),用script標(biāo)簽發(fā)送get請(qǐng)求把函數(shù)名字帶上
前端代碼 <!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
//編寫(xiě)調(diào)用函數(shù)
function getremotedata(data) {
console.log(data);
}
</script>
<!--用script標(biāo)簽get方法把數(shù)據(jù)請(qǐng)求發(fā)送到后端-->
<script src="http://localhost:3999/?callback=getremotedata"></script>
</body>
</html>后端代碼 //用node編寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器
const http = require('http');
const urlModule = require('url');
const server = http.createServer();
server.on('request', function (req, res) {
//urlModule.parse(req.url.url)的請(qǐng)求 就是這個(gè)對(duì)象
// {
// protocol: null,
// slashes: null,
// auth: null,
// host: null,
// port: null,
// hostname: null,
// hash: null,
// search: '?callback=getremotedata',
// query: 'callback=getremotedata',
// pathname: '/',
// path: '/?callback=getremotedata',
// href: '/?callback=getremotedata' }
// 對(duì)象結(jié)構(gòu)賦值得到query是一個(gè)對(duì)象
const {pathname: url, query} = urlModule.parse(req.url, true)
if (url === '/') {
var data = {
name: '大毛',
age: 18,
gender: '未知'
};
// 解析query的請(qǐng)求得到前端發(fā)送的函數(shù)名稱(chēng),加上括號(hào)調(diào)用此函數(shù),函數(shù)里加實(shí)參servedata返回
var scripteStr = `${query.callback}(${JSON.stringify(data)})`
console.log(scripteStr)
res.end(scripteStr)
} else {
res.end('404')
}
});
server.listen('3999', function () {
console.log('server is running 3999')
})這樣前端發(fā)送請(qǐng)求,無(wú)論回調(diào)是什么,后端都會(huì)返回回調(diào)加data數(shù)據(jù),就實(shí)現(xiàn)了跨域請(qǐng)求啦。 第一寫(xiě)感覺(jué)有點(diǎn)語(yǔ)言不清,大家把代碼自己敲一遍就懂了 自學(xué)前端3個(gè)月,想找一個(gè)基礎(chǔ)的前端工作 以上就是JSONP跨域請(qǐng)求的理解(代碼示例)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章! 網(wǎng)站建設(shè)是一個(gè)廣義的術(shù)語(yǔ),涵蓋了許多不同的技能和學(xué)科中所使用的生產(chǎn)和維護(hù)的網(wǎng)站。 |
溫馨提示:喜歡本站的話,請(qǐng)收藏一下本站!