html:
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8"><title>表单示例</title>
</head>
<body><!-- 创建表单 --><form action="form.php" method="post" id="myForm"><!-- 普通文字输入框 --><label for="normalText">普通文字:</label><input type="text" id="normalText" name="normalText" value="请输入普通文字"><br><br><label for="picture">图片<label><input type="file" single accept=".png,.jpg" id="pictureAddr" name="pictureAddr"><br><br><!-- 用户名输入框 --><label for="username">用户名:</label><input type="text" id="username" name="username"><br><br><!-- 密码输入框 --><label for="password">密码:</label><input type="password" id="password" name="password"><br><br><!-- 提交按钮 --><input type="submit" value="提交"></form><script type="text/javascript">var fileUP = document.getElementById('pictureAddr');var myForm = document.getElementById('myForm');//拦截表单的submit事件, 然后根据自己的逻辑选择提交myForm.addEventListener('submit', function(e) {e.preventDefault();if (fileUP.value == null || fileUP.value == '') {console.log('图片不能为空');} else {console.log(fileUP.value);this.submit();}});//监听input文件选择的变化fileUP.addEventListener('change', function(e) {console.log(e.target.files);if (e.target.files.length == 0)return;var t_file = e.target.files[0];if (t_file.name.indexOf('jpg')!=-1 || t_file.name.indexOf('png')!=-1) {console.log('是图片');} else {console.log('文件类型错误');fileUP.value = null;}}, false);</script>
</body>
</html>
form.php:
<?php
// 设置默认字符集为UTF-8
header('Content-Type: text/html; charset=utf-8');// 检查是否提交了表单
if ($_SERVER['REQUEST_METHOD'] == 'POST') {// 获取用户输入的用户名和密码$username = $_POST['username'];$password = $_POST['password'];// 验证用户名和密码是否正确(这里仅作示例,实际应用中需要连接数据库进行验证)if ($username == "admin" && $password == "123456") {echo '登录成功'. "<br>";}
}
?>