在URL中存储变量通常是通过查询参数(query parameters)来实现的。查询参数是URL中?
符号后面的键值对,用于向服务器传递额外的信息。以下是如何在URL中使用查询参数的详细步骤:
假设你想在URL中传递一个名为userId
的变量,值为123
,你可以这样构建URL:
https://example.com/page?userId=123
不同的编程语言有不同的方法来构建带有查询参数的URL。以下是一些常见编程语言的示例:
const baseUrl = 'https://example.com/page';
const params = new URLSearchParams({ userId: '123' });
const url = `${baseUrl}?${params.toString()}`;
console.log(url); // 输出: https://example.com/page?userId=123
from urllib.parse import urlencode
base_url = 'https://example.com/page'
params = {'userId': '123'}
url = f"{base_url}?{urlencode(params)}"
print(url) # 输出: https://example.com/page?userId=123
$baseUrl = 'https://example.com/page';
$params = ['userId' => '123'];
$url = $baseUrl . '?' . http_build_query($params);
echo $url; // 输出: https://example.com/page?userId=123
当你接收到一个带有查询参数的URL时,你可以从中提取这些参数。以下是一些常见编程语言的示例:
const url = new URL('https://example.com/page?userId=123');
const userId = url.searchParams.get('userId');
console.log(userId); // 输出: 123
from urllib.parse import urlparse, parse_qs
url = 'https://example.com/page?userId=123'
parsed_url = urlparse(url)
params = parse_qs(parsed_url.query)
userId = params['userId'][0]
print(userId) # 输出: 123
$url = 'https://example.com/page?userId=123';
parse_str(parse_url($url, PHP_URL_QUERY), $params);
$userId = $params['userId'];
echo $userId; // 输出: 123
领取专属 10元无门槛券
手把手带您无忧上云