【发布时间】:2021-09-18 14:48:47
【问题描述】:
是否有可用于以下代码 sn-p 的 vanilla javascript 替代方案?
function check() {
var restURL = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email').value + "&smtp=1&format=1"
$.ajax({
type: 'GET',
url: restURL,
dataType: "json",
success: renderList,
});
return false;
}
function renderList(data) {
if ((data.format_valid == true) && (data.smtp_check == true)) {
alert("Valid email");
}
else {
alert("Invalid email");
}
}
这是我使用 jQuery 的唯一地方,并且为此使用整个 jQuery 库听起来不是一个好主意。我已经测试了用于电子邮件验证的脚本,它运行良好。
当我发现 jQuery Ajax 的 VanillaJS 替代品时,我遇到了http://youmightnotneedjquery.com/,这是我可以使用该网站编写的代码,但它根本没有显示任何输出:
function check() {
var restURL = "https://apilayer.net/api/check?access_key=c5118f1f9827f42a5fc4b231932130a8&email=" + document.getElementById('email').value + "&smtp=1&format=1"
var request = new XMLHttpRequest();
request.open('GET', restURL, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
//SUCCESS
var resp = this.response;
renderList(resp.data);
} else {
// We reached our target server, but it returned an error
alert("Server returned an error");
}
};
request.onerror = function() {
alert("Connection Error");
// There was a connection error of some sort
};
request.send();
}
function renderList(data) {
if ((data.format_valid == true) && (data.smtp_check == true)) {
alert("Valid email");
} else {
alert("Invalid email");
}
}
<input type="email" id="email" value="x@.com" />
<button onclick="check()"> Click me</button>
【问题讨论】:
-
我给你做了一个sn-p。你在某个地方给
check打过电话吗?代码看起来正确并运行 -
你可能想换行:
+encodeURIComponent(document.getElementById('email').value )+... -
@mplungjan 不,它不显示任何输出。我将编辑帖子并放置访问密钥,以便您查看
-
@mplungjan 我已经使用访问密钥更新了 jquery 和 vanillaJS 代码,并且还包含了 html,现在您可以运行它们并自行检查。
-
对于未来的编辑,请直接编辑 sn-p。让您更轻松地查看代码的运行情况。
标签: javascript jquery ajax api email-validation