如何在 JavaScript 中建立查詢引數?
現在,問題是我們為什麼要使用 JavaScript 建立查詢引數。讓我們透過現實生活中的例子來理解它。
例如,如果您訪問亞馬遜網站並搜尋任何產品,您會看到它會自動將您的搜尋查詢附加到 URL 中。這意味著我們需要根據搜尋查詢生成查詢引數。
此外,我們可以允許使用者從下拉選項中選擇任何值。我們可以生成查詢引數並根據所選值將使用者重定向到新的 URL 以獲取結果。在本教程中,我們將學習如何建立查詢引數。
在這裡,我們將看到建立查詢引數的不同示例。
使用 encodeURIComponent() 方法
encodeURIComponent() 方法允許我們對 URL 的特殊字元進行編碼。例如,URL 不包含空格。因此,我們需要用“%20”字串替換空格字元,“%20”字串表示空格字元的編碼格式。
此外,encodedURLComponent() 用於對 URL 的元件進行編碼,而不是對整個 URL 進行編碼。
語法
使用者可以按照以下語法建立查詢引數並使用編碼的 URI 元件 () 方法對其進行編碼。
queryString += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
在上面的語法中,key 是要為查詢引數設定的鍵,value 與查詢引數的特定鍵相關。我們使用“=”字元分隔鍵和值,使用“&”字元分隔兩個查詢。
示例 1
在下面的示例中,我們建立了物件並存儲了鍵值對。使用物件的鍵和值,我們建立了查詢引數。之後,for-of 迴圈遍歷物件,逐個獲取鍵值對,並使用 encodeURIComponent() 方法生成編碼字串。
最後,我們獲取了長度等於 queryString 長度 -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>
在本教程中,使用者學習瞭如何從不同的資料建立查詢引數。我們學習瞭如何從物件資料建立查詢引數。此外,我們還學習瞭如何使用使用者輸入建立查詢引數,這在向網站新增搜尋功能時非常有用。