JS?中的URLSearchParams?對象操作(以對象的形式上傳參數(shù)到url)
更新時間:2022年12月13日 15:26:28 作者:謝友海
這篇文章主要介紹了JS中URLSearchParams的基本用法,本文結合示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
基本用法
此功能某些瀏覽器尚在開發(fā)中,兼容性可能不是很好。
URLSearchParams()
構造器:創(chuàng)建并返回一個新的URLSearchParams
對象。 開頭的’?
’ 字符會被忽略。
語法:
// init: 參數(shù)可選,為一個 USVString var URLSearchParams = new URLSearchParams(init);
示例:
// 傳入一個字符串字面值 var searchParams = new URLSearchParams('https://example.com?foo=1&bar=2'); console.log(searchParams.toString()); // foo=1&bar=2 // 查找字符串 console.log(searchParams.has('foo')); // true // 獲取字符串對應的數(shù)據(jù) console.log(searchParams.get('foo')); // 1 // 設置字符串 searchParams.set('ttl','3'); // 1 console.log(searchParams.toString()); // foo=1&bar=2&ttl=3 // 傳入一個 sequence var params3 = new URLSearchParams([["foo", 1],["bar", 2]]); console.log(params3.toString()); // foo=1&bar=2 // 傳入一個 record var params4 = new URLSearchParams({"foo" : 1 , "bar" : 2}); console.log(params4.toString()); // foo=1&bar=2
url的打印結果:
實踐運用
函數(shù)封裝:
export function toSearch(record: Record<string, string>) { return new URLSearchParams(record).toString(); }
使用
// Button 按鈕是adtd里面的,這里只展示局部代碼 <Button type="link" href={`#/project/flowpage?${toSearch({ id: 666, name: "liu", })}`} target="_blank" > 點擊按鈕 </Button>
效果:
// 前面域名指向當前網(wǎng)頁的域名,這里暫用...省略 ...#/project/flowpage?id=666&name="liu"
到此這篇關于JS 中的URLSearchParams 對象操作(以對象的形式上傳參數(shù)到url)的文章就介紹到這了,更多相關JS URLSearchParams內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Bootstrap3 input輸入框插入glyphicon圖標的方法
這篇文章主要介紹了Bootstrap3 input輸入框插入glyphicon圖標的方法的相關資料,需要的朋友可以參考下2016-05-05JavaScript實現(xiàn)強制重定向至HTTPS頁面
這篇文章主要介紹了JavaScript實現(xiàn)強制重定向至HTTPS頁面,本文講解如何用JS實現(xiàn)HTTP重定向HTTPS或者HTTPS跳轉到HTTP,需要的朋友可以參考下2015-06-06