JSONP使用動態(tài)創(chuàng)建script實現(xiàn)的锣披,動態(tài)創(chuàng)建script只能使用GET不能使用POST原环。
用 form 可以發(fā)請求挠唆,但是會刷新頁面或新開頁面
用 a 可以發(fā) get 請求,但是也會刷新頁面或新開頁面
用 img 可以發(fā) get 請求嘱吗,但是只能以圖片的形式展示
用 link 可以發(fā) get 請求玄组,但是只能以 CSS、favicon 的形式展示
用 script 可以發(fā) get 請求谒麦,但是只能以腳本的形式運行
JSONP
請求方:xxx.com 的前端程序員(瀏覽器)
響應(yīng)方:yyy.com 的后端程序員(服務(wù)器)
請求方創(chuàng)建 script俄讹,src 指向響應(yīng)方,同時傳一個查詢參數(shù) ?callbackName=yyy
響應(yīng)方根據(jù)查詢參數(shù)callbackName绕德,構(gòu)造形如
yyy.call(undefined, '你要的數(shù)據(jù)')
yyy('你要的數(shù)據(jù)')
這樣的響應(yīng)
瀏覽器接收到響應(yīng)患膛,就會執(zhí)行 yyy.call(undefined, '你要的數(shù)據(jù)')
那么請求方就知道了他要的數(shù)據(jù)
一個用script標簽更新頁面信息的方法
node.js
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]
if(!port){
console.log('請指定端口號好不啦?\nnode server.js 8888 這樣不會嗎耻蛇?')
process.exit(1)
}
var server = http.createServer(function(request, response){
var parsedUrl = url.parse(request.url, true)
var path = request.url
var query = ''
if(path.indexOf('?') >= 0){ query = path.substring(path.indexOf('?')) }
var pathNoQuery = parsedUrl.pathname
var queryObject = parsedUrl.query
var method = request.method
console.log('HTTP 路徑為\n' + path)
if(path == '/'){
var string = fs.readFileSync('./index.html','utf8')
var amount = fs.readFileSync('./db','utf8')
string = string.replace('&&amount&&',amount)
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.write(string)
response.end()
}else if(path === '/pay'){
var amount = fs.readFileSync('./db','utf8')
var newAmount = amount - 1;
fs.writeFileSync('./db',newAmount)
response.setHeader('Content-Type', 'application/javascript')
response.statuseCode = 200;
response.write(`alert('success')
amount.innerText = amount.innerText - 1
`)
response.end()
}else{
response.statusCode = 404
response.write('找不到對應(yīng)路徑')
response.end()
}
})
server.listen(port)
console.log('監(jiān)聽 ' + port + ' 成功\n請用在空中轉(zhuǎn)體720度然后用電飯煲打開 http://localhost:' + port)
前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nodejs-test</title>
</head>
<body>
<p>您的余額:<span id='amount'>&&amount&&</span></p>
<input type='text' name='number' value='1'>
<input type='submit' value='付款一元' id='button'>
<script>
button.addEventListener('click',(e)=>{
let script = document.createElement('script')
script.src='/pay'
document.body.appendChild(script)
script.onload = function(e){
e.currentTarget.remove()
}
script.onerror = function(){
alert('fail')
e.currentTarget.remove()
}
})
</script>
</body>
</html>
jsonp
node.js
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]
if(!port){
console.log('請指定端口號好不啦踪蹬?\nnode server.js 8888 這樣不會嗎?')
process.exit(1)
}
var server = http.createServer(function(request, response){
var parsedUrl = url.parse(request.url, true)
var path = request.url
var query = parsedUrl.query
var pathNoQuery = parsedUrl.pathname
var queryObject = parsedUrl.query
var method = request.method
console.log('HTTP 路徑為\n' + path)
if(path == '/style.css'){
response.setHeader('Content-Type', 'text/css; charset=utf-8')
response.write('body{background-color: #ddd;}h1{color: red;}')
response.end()
}else if(path == '/main.js'){
response.setHeader('Content-Type', 'text/javascript; charset=utf-8')
response.write('alert("這是JS執(zhí)行的")')
response.end()
}else if(path == '/'){
var string = fs.readFileSync('./index.html','utf8')
var amount = fs.readFileSync('./db','utf8')
string = string.replace('&&amount&&',amount)
response.setHeader('Content-Type', 'text/html; charset=utf-8')
response.write(string)
response.end()
}else if(pathNoQuery === '/pay'){
var amount = fs.readFileSync('./db','utf8')
var newAmount = amount - 1;
fs.writeFileSync('./db',newAmount)
response.setHeader('Content-Type', 'application/javascript')
response.statuseCode = 200;
response.write(`
${query.callback}.call(undefined,'success')
`)
response.end()
}else{
response.statusCode = 404
response.write('找不到對應(yīng)路徑')
response.end()
}
})
server.listen(port)
console.log('監(jiān)聽 ' + port + ' 成功\n請用在空中轉(zhuǎn)體720度然后用電飯煲打開 http://localhost:' + port)
前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>nodejs-test</title>
</head>
<body>
<p>您的余額:<span id='amount'>&&amount&&</span></p>
<input type='text' name='number' value='1'>
<input type='submit' value='付款一元' id='button'>
<script>
button.addEventListener('click',(e)=>{
let fnName = 'xxx' + parseInt(Math.random()*100000)
window[fnName] = function(result){
alert('nikandaole')
alert(`wodedaodejieguoshi${result}`)
amount.innerText = amount.innerText - 1
}
let script = document.createElement('script')
script.src='/pay?callback=' + fnName
document.body.appendChild(script)
script.onload = function(e){
e.currentTarget.remove()
}
script.onerror = function(){
alert('fail')
e.currentTarget.remove()
}
})
</script>
</body>
</html>
使用jquery jsonp
$.ajax({
url: "http://test.com/pay",
dataType: "jsonp",
jsonp: "callback",
success: function( response ) {
amount.innerText = amount.innerText - 1
}
})