一般註冊帳號輸入實務練習 :
<form action="index.html">
帳號:<input type="text" name="account"> <br>
密碼:<input type="password" name="password"> <br>
<input type="button" class="send" value="送出">
</form>
var send = document.querySelector('.send');
send.addEventListener('click',signup,false);
function signup(){}
//抓取表單帳號及密碼輸入的值
var emailStr = document.querySelector('.account').value;
var passwordStr = document.querySelector('.password').value;
//空物件用來裝使用者填入帳號及密碼的值
var account = {};
account.email = emailStr;
account.password = passwordStr;
//AJAX遠端傳值及抓值
var xhr = new XMLHttpRequest();
xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup',true);
xhr.setRequestHeader('Content-type','application/json');
var data = JSON.stringify(account);
xhr.send(data);
responseText
的資料給 JSON.parse 陣列化//本地端判斷有無註冊成功
xhr.onload =function(){
var callbackData = JSON.parse(xhr.responseText);
console.log(callbackData);
var veriStr = callbackData.message;
if(veriStr == "帳號註冊成功"){
alert("您的帳號已經註冊成功了!")
}else{
alert("您的帳號註冊失敗!請重新註冊!")
}
}
練習結果 :
JavaScript碼
var send = document.querySelector('.send');
send.addEventListener('click',signup,false);
function signup(){
//抓取表單帳號及密碼輸入的值
var emailStr = document.querySelector('.account').value;
var passwordStr = document.querySelector('.password').value;
//空物件用來裝使用者填入帳號及密碼的值
var account = {};
account.email = emailStr;
account.password = passwordStr;
//AJAX遠端傳值及抓值
var xhr = new XMLHttpRequest();
xhr.open('post','https://hexschool-tutorial.herokuapp.com/api/signup',true);
xhr.setRequestHeader('Content-type','application/json');
var data = JSON.stringify(account);
xhr.send(data);
//本地端判斷有無註冊成功
xhr.onload =function(){
var callbackData = JSON.parse(xhr.responseText);
console.log(callbackData);
var veriStr = callbackData.message;
if(veriStr == "帳號註冊成功"){
alert("您的帳號已經註冊成功了!")
}else{
alert("您的帳號註冊失敗!請重新註冊!")
}
}
}