当前位置:网站首页>Jsonp function encapsulation
Jsonp function encapsulation
2022-06-25 19:42:00 【Xibing_ G】
encapsulation jsonp The factors that function needs to consider :
( Involving parameter transfer -> function + Request parameters , Need to be encapsulated jsonp Add parameter )
function jsonp(options) {}
1、script Label creation
var script = document.createElement('script');
2、 The parameters to be passed in the request address 、 Splice the parameters
var params = '';
// options Medium data The value is the request parameter to be passed , Is to key=value&key1=value1 To deliver , So further operation is needed
for (var attr in options.data) {
params += '&' + attr + '=' + options.data[attr];
}
3、 Avoid function coverage caused by multiple calls to functions with the same name --> Use random nomenclature ; You need to remove the decimal point of the random number
【 Be careful 】: As mentioned below myJsonp It's casual , The main purpose is Make the function names different , however It can't just be numbers
// Remove the points from the generated random number , And then the function name 'myJsonp' The splice is assigned to fnName
var fnName = 'myJsonp' + Math.random().toString().replace('.', '');
4、 Change the function to script Functions that can be called
Function to success It means carrying out success() You can also execute this function .
but:script The script cannot be executed success Of , Because it is not a global scoped function
so: To change to global scope , That is to say window Next , To use [ ] The format of , Can't use . The format of
Only properties that do exist on the object can be used ., and Variables can only be used [ ]
window[fnName] = options.success;
5、 Set function name 、 Parameters are spliced into the request address , Then assign the request address to script Of src value
Passing the function name along with the arguments avoids “ Manually control that the function names of the server side and the client side are consistent ” Trouble
So dependent on , One on the server side req.query.callback You can get the dynamic function name
script.src = options.url + '?callback=' + fnName + params;
6、 take script Append to page
document.body.appendChild(script);
7、 Avoid multiple calls that result in script Multiple creation of , When triggered onload After the event, delete it from the page
script.addEventListener('load', function() {
document.body.removeChild(script);
})
Call encapsulated jsonp function
The server 3000 client html Code :
<body>
<button id="btn1"> Click me to send a request 1</button>
<script>
var btn1 = document.getElementById('btn1');
btn1.addEventListener('click', function() {
jsonp({
// Request address
url: 'http://localhost:3001/better',
// Request parameters
data: {
firstname: 'xibing',
age: 18
},
success: function(data) {
alert('My name is:' + data.name);
}
})
})
</script>
</body>
The server 3001 Code :( Add the function name and ( Parameters ) Splicing , And then through send Respond to clients )
const express = require('express');
const jsonp = express();
jsonp.get('/better', (req, res) => {
const fnName = req.query.callback;
// Transform the data sent by the client
const name = req.query.firstname + '_G';
// Attention format : Within the object key Corresponding value It needs to be wrapped in double quotation marks
// const result = fnName + '({name:"xibing_G"})';
const result = fnName + '({name:"' + name + '"})';
res.send(result);
})
jsonp.listen(3001);
console.log('3001 Monitored ');
(1)、 There are... In the client transfer request parameters firstname:xibing
(2)、 Server through req.query.firstname Receive and modify , And then put it in the function as an actual parameter response to the client
(3)、 The client executes the response function ( There are already arguments added by the server )
(4)、 Last : A pop-up window in the function body pops up the contents of the client + The data transformed by the server to the parameters passed in by the client .
(5)、 among : The client gets the response content 【 function fnName(.....)】 Start to call the response result ,
Because it has been success Put in global , So here we call success No problem at all .
The principle is :
script It will send a request to the server and execute the contents of the server response
Client side transfer function , The function is modified through the server ( for example : Transfer argument )
The client passes in the arguments and calls this function ( In order to call , Put the function under the global in advance )
边栏推荐
- Force wechat page font size to be 100%
- Kotlin Compose 终结toDo项目 点击可以编辑修改todo
- Bindgetuserinfo will not pop up
- QQ机器人疫情查询/疫情关注等【最新beta2版本】
- Determine whether it is a web page opened on wechat
- QQ机器人官方插件加载配置方法【beta2版本】
- 请问通达信开户安全吗?
- The native JS mobile phone sends SMS cases. After clicking the button, the mobile phone number verification code is sent. The button needs to be disabled and re enabled after 60 seconds
- Can the stock account opened through qiniu school be used? Is the fund safe?
- ECS 7-day practical training camp (Advanced route) -- day04 -- build a portal using ECs and polardb
猜你喜欢
Miner's Diary: why should I go mining on April 5, 2021
Print 1 cute every 100 milliseconds ~ with a running lantern effect
PostgreSQL user role permissions
QQ robot: self forbidden words management of group members [latest beta2 version]
Can GoogleSEO only do content without external chain? (e6zzseo)
Guangzhou Sinovel interactive VR panorama brings development to all walks of life
QQ机器人:群成员自我禁言管理【最新beta2版本】
On location and scale in CNN
Panda weekly -2022/02/18
ActiveMQ--CVE-2016-3088
随机推荐
云上弹性高性能计算,支持生命科学产业高速发展、降本增效
【历史上的今天】6 月 25 日:笔记本之父诞生;Windows 98 发布;通用产品代码首次商用
Uncover ges super large scale graph computing engine hyg: Graph Segmentation
Read multiple associations from a field using delimiters in laravel
Divine reversion EA
PostgreSQL user role permissions
三、HikariCP获取连接流程源码分析三
Can the stock account opened through qiniu school be used? Is the fund safe?
How to quickly close port 8080
Network security detection and prevention test questions (V)
SEO outsourcing reliable company, enterprise SEO outsourcing company which reliable?
Can GoogleSEO only do content without external chain? (e6zzseo)
Genicam gentl standard ver1.5 (1)
Vulnhub range the planes:earth
Google cloud SSH enable root password login
JVM | runtime data area (heap space)
Ali vision AI training camp-day01
One night I worked as an XPath Terminator: XPath Helper Plus
JS some small problems about adding and accessing values to arrays
Tcp/ip test questions (V)