例如,如果您访问亚马逊网站并搜索任何产品,您将看到它会自动将您的搜索查询附加到 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 中创建查询参数?的详细内容。
