当前位置:网站首页>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 )
边栏推荐
- Jump jump games auxiliary (manual version) py code implementation
- Vulnhub range the planes: mercury
- Apifox simple understanding -- the integrator of web side testing
- Vulnhub range - correlation:2
- What is an operator?
- Mysql database design suggestions
- Applet Click to return to the top 2 methods
- Principles of MySQL clustered index and non clustered index
- ECS 7-day practical training camp (Advanced route) -- day01 -- setting up FTP service based on ECS
- Tcp/ip test questions (III)
猜你喜欢

广州华锐互动VR全景为各行各业带来发展
![[C language practice - print the upper triangle and its deformation (with blank version)]](/img/df/f38dc57c6a2de522acd91929ced1ad.png)
[C language practice - print the upper triangle and its deformation (with blank version)]

ECS 7-day practical training camp (Advanced route) -- day04 -- build a portal using ECs and polardb

Kotlin Compose 终结toDo项目 点击可以编辑修改todo

On location and scale in CNN

wooyun-2014-065513

Lilda Bluetooth air conditioning receiver helps create a more comfortable road life

Determine whether it is a web page opened on wechat

云上弹性高性能计算,支持生命科学产业高速发展、降本增效

Automatic fitting when the applet reaches the top
随机推荐
Embark on a new journey and reach the world with wisdom
JS get data
【C语言练习——打印上三角及其变形(带空格版)】
Determine whether it is a web page opened on wechat
Gbpnzd firm offer for 14 months, simulation for 19 months, test stable
[C language practice - print the upper triangle and its deformation (with blank version)]
SQL is used for field data types in various databases
Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology
二、HikariCP獲取連接流程源碼分析二
6、 Configuration resolution of hikariconfig
DataX script task development record
The meanings of /32, /48, /64 in IPv6 addresses
Jump jump games auxiliary (manual version) py code implementation
Ali visual AI training camp -day03- construction of electronic photo album (face and expression recognition)
Lilda Bluetooth air conditioning receiver helps create a more comfortable road life
Network security detection and prevention test questions (V)
mysql load data infile
Miner's Diary: why should I go mining on April 5, 2021
Do you want to know how new investors open accounts? Is online account opening safe?
PostgreSQL change table owner