查询字符串(Query String)是URL中的一部分,通常用于向服务器传递参数。它以问号(?)开头,后面跟着键值对,键值对之间用&符号分隔。例如,在URL https://example.com/page?id=123&name=John
中,id=123
和 name=John
就是查询字符串的一部分。
/cars;color=red;year=2012
。假设我们有一个表单,用户输入的数据需要通过查询字符串传递,并且在页面加载时预先填充这些数据。
以下是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form with Query String</title>
</head>
<body>
<form id="myForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="age">Age:</label>
<input type="text" id="age" name="age"><br><br>
<button type="submit">Submit</button>
</form>
<script>
// Function to get query string parameters
function getQueryStringParams() {
const params = new URLSearchParams(window.location.search);
return Object.fromEntries(params.entries());
}
// Function to populate form fields with query string parameters
function populateFormWithQueryParams() {
const params = getQueryStringParams();
for (const [key, value] of Object.entries(params)) {
const inputField = document.getElementById(key);
if (inputField) {
inputField.value = value;
}
}
}
// Populate the form on page load
window.onload = populateFormWithQueryParams;
</script>
</body>
</html>
URLSearchParams
解析当前URL的查询字符串。populateFormWithQueryParams
函数,确保表单字段被预先填充。通过这种方式,即使表单字段的ID不确定,也可以灵活地从查询字符串中提取数据并填充到相应的字段中。
领取专属 10元无门槛券
手把手带您无忧上云