单邮箱验证器需在当前页展示结果,而非刷新页面显示
实现无刷新邮箱验证(同一页面显示结果)
没问题,咱们把这个邮箱验证改成无刷新提交、同一页面显示结果很简单,分前端调整和后端适配两步来:
一、前端代码修改
首先要调整表单结构,去掉导致新开窗口的target="_blank",再添加一个专门显示验证结果的容器,最后用JavaScript拦截表单提交事件,通过AJAX发送请求。
修改后的HTML表单
<form action="{{ url_for('handle_email') }}" method="post" id="email-form"> <div class="splash"> <!-- 把原来的id="email"改成email-input,避免和表单id重复 --> <input type="text" class="input-box" id="email-input" placeholder="enter email here" name="email"> <p class="splash-subhead"> Email spider can find thousand of emails in seconds. </p> <p> <input type="submit" value="Submit" class="pure-button" id="search-btn"> </p> </div> </form> <!-- 新增:用来展示验证结果的容器 --> <div id="validation-result" style="margin-top: 15px;"></div>
添加JavaScript处理逻辑
把这段代码放在HTML页面的底部(或者<head>里加defer属性),用来拦截表单提交、发送异步请求并展示结果:
document.getElementById('email-form').addEventListener('submit', async function(e) { // 阻止表单默认的刷新提交行为 e.preventDefault(); // 获取输入的邮箱和结果容器 const emailInput = document.getElementById('email-input'); const email = emailInput.value.trim(); const resultContainer = document.getElementById('validation-result'); // 先清空旧结果,显示加载状态(可选) resultContainer.textContent = '验证中...'; // 邮箱为空时提示用户 if (!email) { resultContainer.innerHTML = '<p style="color: orange;">*请输入邮箱地址!</p>'; return; } try { // 发送POST请求到后端接口 const response = await fetch(this.action, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ email: email }) }); const data = await response.json(); // 根据后端返回结果展示不同提示 if (response.ok) { // 这里根据后端实际返回的字段调整,比如假设返回的data里有valid字段 if (data.valid) { resultContainer.innerHTML = `<p style="color: green;">*邮箱 <strong>${email}</strong> 验证有效!</p>`; } else { resultContainer.innerHTML = `<p style="color: red;">*邮箱 <strong>${email}</strong> 无效!</p>`; } } else { resultContainer.innerHTML = `<p style="color: red;">*验证出错:${data.response || '未知错误'}</p>`; } } catch (error) { resultContainer.innerHTML = '<p style="color: red;">*网络错误,请稍后重试!</p>'; console.error('请求异常:', error); } });
二、后端代码适配
你的现有后端代码基本不需要大改,已经能返回JSON格式的结果了,只需要注意两个细节:
- 确保已经安装了
requests库:如果没装,运行pip install requests - 如果前端和后端是跨域名部署的(比如前端在localhost:8080,后端在localhost:5000),需要处理跨域问题:
- 安装
flask-cors:pip install flask-cors - 在Flask app里添加配置:
from flask import Flask, request, jsonify from flask_cors import CORS import requests app = Flask(__name__) # 允许所有跨域请求(生产环境建议指定具体域名) CORS(app) @app.route('/email', methods=['POST']) def handle_email(): email = request.form['email'] url = "http://spiderapi.herokuapp.com/api/emails/" print("requesting: ", url) headers = {'Content-type': 'application/json'} r = requests.post(url, json={"email": email, "key": "C88B933A691E16C56EBC92BCC9A7E"}, headers=headers) print(r.json()) if r.status_code == 200: return jsonify(r.json()), 200 else: return jsonify({"response": " Something went wrong ", "status_code": 400}) if __name__ == '__main__': app.run(debug=True) - 安装
这样调整后,用户提交邮箱时页面不会刷新,验证结果会直接显示在表单下方的validation-result容器里啦~
内容的提问来源于stack exchange,提问作者Ashish janghel
相关产品推荐
相关产品推荐

