利用Promise将之前查身份证的小栗子重新修改下.
代码部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AjaxTest2</title>
</head>
<body>
<input id='myInput' type="text" >
<button id='myButton' onclick="handleSubmit()">Click To Down Load</button>
<div id='myDisplay'></div>
>
<script>
const myKey = '0a8c23653d43f9a476add0d0ed833472';
>
function renderHTML(data){
let myDisplay = document.getElementById('myDisplay');
myDisplay.innerHTML = data;
};
>
function formatInfo(data){
let parseData = JSON.parse(data);
let resultCode = parseData.resultcode;
let reason = parseData.reason;
let result = parseData.result;
if (result){
let area = parseData.result.area;
let sex = parseData.result.sex;
let birthday = parseData.result.birthday;
var resultText = '您的出生地为:' + area + ' 您的性别为:' + sex + ' 您的生日为:' + birthday;
}
else {var resultText = reason;}
return resultText;
};
>
function handleHttp(url){
return new Promise(function(resolve,reject){
var myXHR = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject();
myXHR.onload = function() {
if (myXHR.status == 200){
resolve(myXHR.responseText);
}
else {reject(myXHR.statusText);}
};
myXHR.onerror = function() {
reject('Network Error...');
}
>
myXHR.open('GET',url);
myXHR.send();
})
};
>
function handleSubmit(){
let myCard = document.getElementById('myInput').value;
let myURL = 'http://apis.juhe.cn/idcard/index?key=' + myKey + '&cardno=' + myCard;
handleHttp(myURL).then((response)=>{renderHTML(formatInfo(response));}).catch(renderHTML);
};
</script>
</body>
</html>
总结
- 重构之后,handleSubmit看上去更加整洁逻辑一目了然,当然可以把then部分再写个回调.
- handleHttp部分逻辑复用度提升,可以用于各种GET的场合,只要传入url即可. 这边是promise的好处,不用讲异步动作放入主函数内部,而是直接在主函数内部做信号即可. 外部根据信号走回调.
网友评论