llz.html
<h2>llz的网站</h2>
llj.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h2>llj的网站</h2>
<script type="text/javascript">
window['llzUser'] = {}
var script = document.createElement('script')
script.src = 'http://llz.com/xxx.js?name=llzUser'
//script下载的数据
// window['llzUser'] = ({
// "name":"llz",
// "age" : 23
// })
//将替换window['llzUser']的值
script.onload = function(){
console.log('加载xxx.js 成功');
console.log(window['llzUser'])
}
document.head.appendChild(script)
</script>
</body>
</html>
xxx.js
//window['llzUser']
window['{{name}}'] = ({
"name":"llz",
"age" : 23
})
server.js
var http = require('http')
var fs = require('fs')
var url = require('url')
//console.log(Object.keys(http))
var port = process.env.PORT || 80;
var server = http.createServer(function(request, response){
var temp = url.parse(request.url, true)
var path = temp.pathname
var query = temp.query
var method = request.method
if(path === '/'){ // 如果用户请求的是 / 路径
var string = fs.readFileSync('./llz.html', 'utf8')
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.end(string)
}else if(path === '/llz'){
var string = fs.readFileSync('./llz.html', 'utf8')
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.end(string)
}else if(path === '/llj'){
var string = fs.readFileSync('./llj.html', 'utf8')
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.end(string)
}else if(path === '/xxx.js'){
var name = query.name//llzUser
var string = fs.readFileSync('./xxx.js','utf8')
response.setHeader('Access-Control-Allow-Origin','http://llj.com')
response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
response.end(string.replace('{{name}}',name))
}}else{
response.statusCode = 404
response.setHeader('Content-Type', 'text/html;charset=utf-8')
response.end('找不到对应的路径,你需要自行修改 index.js')
}
console.log(method + ' ' + request.url)
})
server.listen(port)
console.log('监听 ' + port + ' 成功,请用在空中转体720度然后用电饭煲打开 http://llz.com:' + port)
在命令行运行(需要下载Node.js)
node server.js
在浏览器URL输入llj.com/llj网址,
网页向http://llz.com/xxx.js?name=llzUser请求脚本并发送请求参数,
server.js会获取请求参数name的值,然后替换xxx.js里的{{name}}字符串,
然后将替换后的内容返回给客户端,
会将页面javascript·里的window['llzUser']变量的值替换。
这里面既有跨域,又有回调函数。
回调函数的话,一般发送的参数名为callback=函数名
网友评论