当前位置:网站首页>Several efficient APIs commonly used in inventory operation URL
Several efficient APIs commonly used in inventory operation URL
2022-07-28 13:57:00 【Maic】
Usually in real projects , No matter what you do data 、 or dom, We need to be familiar with some browser Of API, or js Native gives us extended API, We are familiar with these API, In a sense , Some efficient API and Method It will often solve many difficult and miscellaneous problems encountered in your project .
This article is only about URL Commonly used API, I hope I can bring a little thought and help in your project .
Text begins ...
location object
Under the console ,window.location Get browser address URL Related information
// window.location
/*
https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123
*/
const { href, origin, host, port, protocol,pathname, hash, search } = window.location;
console.log(href) // Get the entire URL xxx
console.log(origin); // agreement + domain name + port https://www.baidu.com
console.log(host); // Host name + Port number (http perhaps https The port number will be omitted ) www.baidu.com
console.log(port); // '' http Default port 80 https Default port 443
console.log(protocol); // agreement https:
console.log(pathname); // In addition to the routing address path of the domain name
console.log(hash); // Path belt # Parameters of
console.log(search); // Address ? All the following parameters
stay location.search、location.hash、location.origin、location.href It is usually a few high-frequency parameter methods to obtain the current address in the project , But note that only location.origin This is read-only , other API It's all readable and writable
URL
stay js Create an address in , Use scenarios , Take a chestnut , We use it URL Simulate the address of the current page
const url = new URL('https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123');
console.log(url.search); // ?wd=Reflect.%20defineProperty&rsv_spt=1
console.log(url.hash); // #123
console.log(url.origin); // https://www.baidu.com
console.log(url.href);// 'https://www.baidu.com/s?wd=Reflect.%20defineProperty&rsv_spt=1#123'
URL The properties in the address of this native construct are the same as location Get the general properties on the address are basically the same . The only difference is ,location More replace And reload Method ,URL Besides having location The general properties of , No, replace And reload Method , But it has a way to get parameters searchParamsAPI
...
console.log(url.searchParams);
// { 'wd' => 'Reflect. defineProperty', 'rsv_spt' => '1' }
console.log(url.searchParams.toString());
// wd=Reflect.+defineProperty&rsv_spt=1
searchParams
Get... Quickly URL Method of carrying parameters in , This is in URL The built address is very convenient . For example, now there is a need , I need to convert the parameters of an address to key And value The key/value pair .
In the past, our practice was like this
function formateQueryUrl () {
const { search } = window.location;
// With ? Division , obtain url The real parameters on
const [, searchStr] = search.split('?');
// With & Parameters before and after segmentation
const arr = searchStr.split('&');
const ret = {};
arr.forEach(v => {
const [key, val] = v.split('=');
ret[key] = val
});
return ret;
}
Now we can make more efficient use of URL Of searchParams
// With the above formateQueryUrl Method equivalence
function eazyFormateQueryUrl() {
const url = new URL(window.location);
return Object.fromEntries(url.searchParams.entries())
}
// If the current browser address https://www.badu.com?a=1&b=2
// {a:1,b:2}
This eazyFormateQueryUrl Is the method simple , Two lines of code will do the formatting url Parameters in , And easily convert a string of string parameters into objects
Note that the above method we used Object.fromEntries And url.searchParams.entries(), Actually url.searchParams The constructor of URLSearchParams, and URLSearchParams It is a system with iterator Functional API, So you can for...of perhaps entries operation .
At the same time, we should pay attention to fromEntries, Let's take a look at this API, Usually we don't often use , Generally, we are entries Much more operation , But actually fromEntries Is to restore the object entries operation , Here we take advantage of this .
Take a chestnut
const ret = {name: 'Maic', public: 'Web Technology academy '};
const arr = Object.entries(ret);
console.log(arr)
// [['name', 'Maic'], ['public', 'Web Technology academy ']]
If you want to arr Restore to previous objects , Then you must think of the circular approach , Like this
...
const target = {};
arr.forEach(item => {
const [key, val] = item;
target[key] = val;
});
console.log(target);
// {name: 'Maic', public: 'Web Technology academy '}
In fact, there is no need to cycle , Native Object Provides a API, It can be entries Restore the data to the previous . Then we can simply implement
const ret = {name: 'Maic', public: 'Web Technology academy '};
const arr = Object.entries(ret);
/* const target = {};
arr.forEach(item => {
const [key, val] = item;
target[key] = val;
});
*/
// Equivalent to
const target = Object.fromEntries(arr)
// {name: 'Maic', public: 'Web Technology academy '}
Because of that , We used fromEntries That's the characteristic of , Skillfully transfer the original data to the object .
about URL, We also need to be able to dynamically add paths , Like a chestnut below
function locationByNamePath (path) {
const { origin } = window.location;
const url = new URL(path, origin);
window.location.href = url.href;
}
locationByNamePath('/index.html');
// https://www.baidu.com/index.html
locationByNamePath('/about.html');
// https://www.baidu.com/about.html
URLSearchParams
This API Is a native constructor , You can get the address ? The following parameter information
Take a chestnut
var urlSearch = new URLSearchParams(window.location.search);
console.log(`${urlSearch}`);
// Open the baidu , Enter a keyword to search on the console , The console copies the broken code , You can see that
URLSearchParams Incoming string
const search = new URLSearchParams('a=1&b=2&c=3');
console.log(search.toString()) // a=1&b=2&c=3
Equivalent to
const search = new URLSearchParams(window.location.search);
console.log(search.toString()) // a=1&b=2&c=3
URLSearchParams Pass in array , Convert an object to url Parameters , Usually in ajaxget When requesting splicing parameters , It could be useful
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
console.log(search2.toString());
//a=1&b=2&c=3
$.ajax({
url: `xxxx?${search2}`,
methods: 'get'
})
When we use fetch Native api When asked ,new URLSearchParams It can be used as body Parameters
const params = {
name: 'maic',
password: '123456'
}
fetch('https://baidu.com', {
methods: 'POST',
body: new URLSearchParams(params)
})
We know URLSearchParams Features that have iterator properties , So it's like Map、Set Same as Add or delete check change Characteristics of
check get Get parameter value
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
console.log(search2.get('a')); // 1
console.log(search2.get('b')); // 2
console.log(search2.get('c')); // 3
increase append, Add a parameter
...
search2.append('d', 'hello')
// a=1&b=2&c=3&d=hello
Delete delete Delete a parameter
...
search2.delete('a');
console.log(search2.toString());
//b=2&c=3
Change set Modify the parameters
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
search2.set('a', '666')
console.log(`${search2}`);
// a=666&b=2&c=3&d=hello
Whether there is has Judge whether there is key
...
console.log(search2.has('a')); // true
obtain URLSearchParams be-all key perhaps value
new URLSearchParams({a:1,b:2,c:3}).keys(),new URLSearchParams({a:1,b:2,c:3}).values()
const obj = {a:1,b:2,c:3};
const search2 = new URLSearchParams(Object.entries(obj));
const keys = Array.from(search2.keys());
console.log(keys);
// ['a', 'b', 'c']
const values = Array.from(search2.values());
// ['1', '2', '3']
about URLSearchParams It can be transmitted character string , It can be object or Array , When we get URLSearchParams Of key, Call directly xxx.keys() Or is it xxx.values(), But the value taken out in this way is an iterator , You need to use Array.from Transfer the .
Restore URLSearchParams Parameters
...
Object.fromEntries(search2.entries());
// {a:1,b:2,c:3}
summary
locationOften gethostname、origin、search、hashetc.URLestablish url, And havesearchParamsobtain url Medium?Later parameters- utilize
URLSearchParamsEfficient formattingurlParameters , Two lines of code realize the formatting?Parameters URLSearchParamsThisAPIYou can get it directly url Parameters , And provideAdd or delete check change[append、delete、get、set、has] Method
边栏推荐
- Graph traversal (BFS & DFS basis)
- To build agile teams, these methods are indispensable
- 数据库系统原理与应用教程(062)—— MySQL 练习题:操作题 32-38(六)
- JWT 登录认证 + Token 自动续期方案,写得太好了!
- 30 day question brushing plan (III)
- Children's programming electronic society graphical programming level examination scratch Level 2 real problem analysis (judgment question) June 2022
- 记一次COOKIE的伪造登录
- Li Kou sword finger offer 51. reverse order pairs in the array
- Qt5 development from introduction to mastery -- the first overview
- 使用 Fail2ban 保护 Web 服务器免受 DDoS 攻击
猜你喜欢

Qt5开发从入门到精通——第一篇概述

111. The sap ui5 fileuploader control realizes local file upload and encounters a cross domain access error when receiving the response from the server

Countdown 2 days! 2022 China Computing Conference: Mobile cloud invites you to meet with computing network for innovative development

The domestic API management tool eolink is very easy to use, creating an efficient research and development tool

使用 IPtables 进行 DDoS 保护

111. SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误

第六章 支持向量机

What is the reason why the words behind word disappear when typing? How to solve it?

Product Manager: job responsibility table

30天刷题计划(四)
随机推荐
UVA1599理想路径题解
国产API管理工具Eolink太好用了,打造高效的研发利器
R语言使用lm函数构建多元回归模型(Multiple Linear Regression)、并根据模型系数写出回归方程、使用confint函数给出回归系数的95%置信区间
彻底掌握二分查找
Tutorial on the principle and application of database system (059) -- MySQL exercise questions: operation questions 1-10 (III)
.net for subtraction, intersection and union of complex type sets
The strongest distributed locking tool: redisson
R language uses LM function to build multiple linear regression model, writes regression equation according to model coefficient, and uses conflict function to give 95% confidence interval of regressi
Dojnoip201708 cheese solution
SAP UI5 FileUploader 控件实现本地文件上传,接收服务器端的响应时遇到跨域访问错误的试读版
Socket class understanding and learning about TCP character stream programming
SLAM论文合集
R语言ggplot2可视化:使用ggpubr包的ggviolin函数可视化小提琴图、设置draw_quantiles参数添加指定分位数横线(例如,50%分位数、中位数)
掌握闭包,夯实基本功
Uva11175 digraph D and E from D to e and back
Graph traversal (BFS & DFS basis)
JWT 登录认证 + Token 自动续期方案,写得太好了!
[C language] the difference between structure pointer and structure variable as formal parameters
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
7. Dependency injection