首頁  >  文章  >  web前端  >  如何在 JavaScript 中建立查詢參數?

如何在 JavaScript 中建立查詢參數?

王林
王林轉載
2023-09-21 15:53:02881瀏覽

如何在 JavaScript 中创建查询参数?

現在的問題是為什麼我們需要使用 JavaScript 來建立查詢參數。讓我們透過現實生活中的例子來理解它。

例如,如果您造訪亞馬遜網站並蒐索任何產品,您將看到它會自動將您的搜尋查詢附加到 URL。這意味著我們需要從搜尋查詢中產生查詢參數。

此外,我們可以允許使用者從下拉選項中選擇任何值。我們可以產生查詢參數並根據所選值將使用者重新導向到新的 URL 以獲得結果。我們將在本教程中學習建立查詢參數。

在這裡,我們將看到建立查詢參數的不同範例。

使用encodeURIComponent()方法

encodeURIComponent() 方法讓我們可以對 URL 的特殊字元進行編碼。例如,URL 不包含空格。因此,我們需要將空格字元替換為‘ ’字串,代表空格字元的編碼格式。

此外,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 中建立查詢參數?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除