現在的問題是為什么我們需要使用 JavaScript 創建查詢參數。讓我們通過現實生活中的例子來理解它。
例如,如果您訪問亞馬遜網站并搜索任何產品,您將看到它會自動將您的搜索查詢附加到 URL。這意味著我們需要從搜索查詢生成查詢參數。
此外,我們可以允許用戶從下拉選項中選擇任何值。我們可以生成查詢參數并根據所選值將用戶重定向到新的 URL 以獲得結果。我們將在本教程中學習創建查詢參數。
在這里,我們將看到創建查詢參數的不同示例。
使用encodeURIComponent()方法
encodeURIComponent() 方法允許我們對 URL 的特殊字符進行編碼。例如,URL 不包含空格。因此,我們需要將空格字符替換為‘%20’字符串,代表空格字符的編碼格式。
此外,encodedURLComponent() 用于對 URL 的組成部分進行編碼,而不是對整個 URL 進行編碼。
語法
用戶可以按照以下語法創建查詢參數,并使用編碼的 URI 組件 () 方法對其進行編碼。
queryString += encodeURIComponent(key) + '='
+ encodeURIComponent(value) + '&';
登錄后復制
在上面的語法中,key是為查詢參數設置的key,value與查詢參數的特定key相關。我們使用“=”字符分隔鍵和值,并使用“&”字符分隔兩個查詢。
示例 1
在下面的示例中,我們創建了對象并存儲了鍵值對。使用對象的鍵和值,我們創建查詢參數。之后,for-of 循??環遍歷對象,獲取一對一的鍵值對,并使用encodedURIComponent() 方法生成編碼字符串。
最后,我們取了長度等于查詢字符串長度-1的子字符串,以刪除最后一個“&”字符。
<html>
<body>
<h2>Using the <i>encodedURIComponent() method</i> to Create query params using JavaScript </h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let objectData = {
'search': 'JavaScript',
'keyword': 'query params.'
}
let queryString = ""
for (let key in objectData) {
queryString += encodeURIComponent(key) + '='
+ encodeURIComponent(objectData[key]) + '&';
}
queryString = queryString.substr(0, queryString.length - 1)
output.innerHTML += "The encoded query params is " + queryString;
</script>
</body>
</html>
登錄后復制
示例 2
在此示例中,我們將用戶輸入作為查詢參數的數據。我們使用了prompt()方法來獲取用戶輸入,該方法從用戶那里一一獲取鍵和值。
之后,我們使用encodeURIComponent() 方法使用用戶輸入值來創建查詢參數。
<html>
<body>
<h2>Using the <i>encodedURIComponent() method</i> to Create query params of user input values</h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let param1 = prompt("Enter the key for the first query", "key1");
let value1 = prompt("Enter the value for the first query", "value1");
let param2 = prompt("Enter the key for the second query", "key2");
let value2 = prompt("Enter the value for the second query", "value2");
let queryString = ""
queryString += encodeURIComponent(param1) + '='
+ encodeURIComponent(value1) + '&';
queryString += encodeURIComponent(param2) + '='
+ encodeURIComponent(value2);
output.innerHTML += "The encoded query string from the user input is " + queryString;
</script>
</body>
</html>
登錄后復制
在本教程中,用戶學習了如何從不同的數據創建查詢參數。我們學會了從對象數據中創建查詢參數。此外,我們還學會了使用用戶輸入來創建查詢參數,這在向網站添加搜索功能時非常有用。
以上就是如何在 JavaScript 中創建查詢參數?的詳細內容,更多請關注www.92cms.cn其它相關文章!






