現(xiàn)在的問(wèn)題是為什么我們需要使用 JavaScript 創(chuàng)建查詢(xún)參數(shù)。讓我們通過(guò)現(xiàn)實(shí)生活中的例子來(lái)理解它。
例如,如果您訪(fǎng)問(wèn)亞馬遜網(wǎng)站并搜索任何產(chǎn)品,您將看到它會(huì)自動(dòng)將您的搜索查詢(xún)附加到 URL。這意味著我們需要從搜索查詢(xún)生成查詢(xún)參數(shù)。
此外,我們可以允許用戶(hù)從下拉選項(xiàng)中選擇任何值。我們可以生成查詢(xún)參數(shù)并根據(jù)所選值將用戶(hù)重定向到新的 URL 以獲得結(jié)果。我們將在本教程中學(xué)習(xí)創(chuàng)建查詢(xún)參數(shù)。
在這里,我們將看到創(chuàng)建查詢(xún)參數(shù)的不同示例。
使用encodeURIComponent()方法
encodeURIComponent() 方法允許我們對(duì) URL 的特殊字符進(jìn)行編碼。例如,URL 不包含空格。因此,我們需要將空格字符替換為‘%20’字符串,代表空格字符的編碼格式。
此外,encodedURLComponent() 用于對(duì) URL 的組成部分進(jìn)行編碼,而不是對(duì)整個(gè) URL 進(jìn)行編碼。
語(yǔ)法
用戶(hù)可以按照以下語(yǔ)法創(chuàng)建查詢(xún)參數(shù),并使用編碼的 URI 組件 () 方法對(duì)其進(jìn)行編碼。
queryString += encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&';
登錄后復(fù)制
在上面的語(yǔ)法中,key是為查詢(xún)參數(shù)設(shè)置的key,value與查詢(xún)參數(shù)的特定key相關(guān)。我們使用“=”字符分隔鍵和值,并使用“&”字符分隔兩個(gè)查詢(xún)。
示例 1
在下面的示例中,我們創(chuàng)建了對(duì)象并存儲(chǔ)了鍵值對(duì)。使用對(duì)象的鍵和值,我們創(chuàng)建查詢(xún)參數(shù)。之后,for-of 循??環(huán)遍歷對(duì)象,獲取一對(duì)一的鍵值對(duì),并使用encodedURIComponent() 方法生成編碼字符串。
最后,我們?nèi)×碎L(zhǎng)度等于查詢(xún)字符串長(zhǎng)度-1的子字符串,以刪除最后一個(gè)“&”字符。
<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>
登錄后復(fù)制
示例 2
在此示例中,我們將用戶(hù)輸入作為查詢(xún)參數(shù)的數(shù)據(jù)。我們使用了prompt()方法來(lái)獲取用戶(hù)輸入,該方法從用戶(hù)那里一一獲取鍵和值。
之后,我們使用encodeURIComponent() 方法使用用戶(hù)輸入值來(lái)創(chuàng)建查詢(xún)參數(shù)。
<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>
登錄后復(fù)制
在本教程中,用戶(hù)學(xué)習(xí)了如何從不同的數(shù)據(jù)創(chuàng)建查詢(xún)參數(shù)。我們學(xué)會(huì)了從對(duì)象數(shù)據(jù)中創(chuàng)建查詢(xún)參數(shù)。此外,我們還學(xué)會(huì)了使用用戶(hù)輸入來(lái)創(chuàng)建查詢(xún)參數(shù),這在向網(wǎng)站添加搜索功能時(shí)非常有用。
以上就是如何在 JavaScript 中創(chuàng)建查詢(xún)參數(shù)?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!