在页面上通过表单提交当前时间
时间: 2024-05-10 15:17:02 浏览: 6
好的,您需要在页面上添加一个表单,并在表单中添加一个按钮,点击按钮时可以获取当前时间并将其提交到服务器。以下是一个示例代码:
```html
<form>
<button onclick="submitForm()">提交时间</button>
</form>
<script>
function submitForm() {
var currentTime = new Date().toLocaleString();
var formData = new FormData();
formData.append("currentTime", currentTime);
fetch("/submit-time", {
method: "POST",
body: formData
})
.then(response => {
console.log("时间已提交");
})
.catch(error => {
console.error(error);
});
}
</script>
```
在这个示例中,我们使用了 JavaScript 的 `Date` 对象来获取当前时间,并将其转换为本地时间格式。然后,我们创建了一个 `FormData` 对象,并向其中添加了一个名为 `currentTime` 的字段,其值为当前时间。最后,我们使用 `fetch` 方法将表单数据提交到服务器的 `/submit-time` 路径。您需要在服务器端编写代码来接收并处理这个请求。
相关问题
在页面上通过表单提交当前时间,如果时间介于6:00-18:00,属于白天。根据时间,在页面上分别显示白天图片和黑夜图片
可以通过以下代码实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>时间判断</title>
</head>
<body>
<form id="form">
<label for="time">当前时间:</label>
<input type="time" id="time" name="time">
<button type="submit">提交</button>
</form>
<img id="image" src="">
<script>
const form = document.getElementById('form');
const image = document.getElementById('image');
form.addEventListener('submit', (event) => {
event.preventDefault();
const time = form.time.value;
const hour = parseInt(time.split(':')[0]);
if (hour >= 6 && hour < 18) {
image.src = 'daytime.jpg';
} else {
image.src = 'nighttime.jpg';
}
});
</script>
</body>
</html>
```
在上面的代码中,我们通过 `form` 表单获取用户提交的时间,然后根据时间的小时数判断是白天还是黑夜,最后将对应的图片显示在页面上。
在页面上通过表单提交当前时间,如果时间介于6:00-18:00,属于白天。根据时间,在页面上分别显示白天图片和黑夜图片
可以通过JavaScript获取当前时间,并根据时间判断应该显示哪张图片。以下是示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Day and Night Images</title>
</head>
<body>
<form>
<input type="button" value="Show Image" onclick="showImage()">
</form>
<div id="image-container"></div>
<script>
function showImage() {
var now = new Date();
var hour = now.getHours();
var imageContainer = document.getElementById("image-container");
if (hour >= 6 && hour < 18) {
imageContainer.innerHTML = "<img src='day.jpg'>";
} else {
imageContainer.innerHTML = "<img src='night.jpg'>";
}
}
</script>
</body>
</html>
```
在上面的代码中,我们使用了一个表单,其中有一个按钮,点击该按钮会调用`showImage()`函数。在`showImage()`函数中,我们获取当前时间,并根据小时数判断应该显示哪张图片。如果当前时间在6:00-18:00之间,显示白天图片,否则显示黑夜图片。最后,我们将图片插入到页面中的一个`<div>`元素中。