短信验证码注册登录就是验证用户提交的手机验证码,如果验证码验证错误,就提示“验证码错误”,如果验证正确,那就进入到注册成功的页面。
这几天一直在研究JavaScript实现短信验证码注册登录的方法,主要是因为项目需求(现在好像几乎所有的项目都需要验证码注册登录),整理了三种对接方法,可供大家学习和参考:
Fetch方法
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
var urlencoded = new URLSearchParams();
urlencoded.append("appId", "41KYR0EB****");
urlencoded.append("appKey", "IIWCKKSR7NOQ****");
urlencoded.append("phone", "1561894****");
urlencoded.append("templateId", "1043");
urlencoded.append("variables", "1234");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://vip.veesing.com/smsApi/verifyCode", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
jQuery方法
var settings = {
"url": "https://vip.veesing.com/smsApi/verifyCode",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
},
"data": {
"appId": "41KYR0EB****",
"appKey": "IIWCKKSR7NOQ****",
"phone": "1561894****",
"templateId": "1043",
"variables": "1234"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
XHR方法
var data = "appId=41KYR0EB****&appKey=IIWCKKSR7NOQ****&phone=1561894****&templateId=1043&variables=1234";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://vip.veesing.com/smsApi/verifyCode");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.send(data);
以上就是JavaScript实现短信验证码登录注册的3种方法,有疑问可以在评论区指出,欢迎和大家一起讨论。
JavaScript - Fetch.js、JavaScript - jQuery、JavaScript - XHR.js文件下载
来源:oschina
链接:https://my.oschina.net/u/3937044/blog/4750552