假设我有这样的REST api:
(我可以要求提供合同清单)
要求:获取www.domain.com/contracts/list
回应:
[{"contractId": 1, "contractDate":"2017-05-26", "partnerId": 1},
{"contractId": 2, "contractDate":"2017-05-26", "partnerId": 2},
{"contractId": 3, "contractDate":"2017-05-26", "partnerId": 1}, {more JSON Objects ...}]
(我可以要求合作伙伴{id}是参数)
要求:获取www.domain.com/partners/{id}
回复:{"partenerId": 1, "name":"StackOverflow", "bankAccountsId":[{"bankAccountId": 7}, {"bankAccountId": 33}]}
(我可以要求BankAccounts)
请求:获取www.domain.com/bankaccounts/{id}
回复:{"bankAccountId":7, "iban":"124531YDS51625316126", "bankId": 25}
(我可以要求银行)
要求:获取www.domain.com/banks/{id}
回复:{"bankId":25, "name":"CityBank"}
从Javascript中显示列表的正确方法是什么:
合同ID:1
合约日期:26.05.2017
合作伙伴名称:Stackoverflow
银行账户:
124531YDS51625316126 CityBank
128737ING01231623812 ING
.....更多....
此时我使用Ajax Calls(Promises)和Closures的组合来呈现列表我将向您展示如何但我觉得它不正确并且在我看来非常复杂(我使用Jquery作为Axaj调用并且不使用ES6功能):
function render() {
var output = document.createDocumentFragment();
jQuery.ajax({
method: 'GET',
url: 'https://www.example.com/contacts/list'
}).done(function(contracts){
for (var i=0, l=contracts.length; i<l; i++) {
var div = document.createElement('div');
div.innerHTML = contracts[i].contractId;
output.appendChild(div);
var div = document.createElement('div');
div.innerHTML = contracts[i].contractDate;
output.appendChild(div);
var div = document.createElement('div');
output.appendChild(div);
(function (place, _partenerId) {
jQuery.ajax({
method: 'GET',
url: 'https://www.example.com/partners/',
data: {partenerId:_partenerId}
}).done(function(partner){
place.innerHTML = partner.name;
for (var j=0; j<partener.bankAccountsId.length; j++) {
(function(place, _bankAccountId) {
jQuery.ajax({
method: 'GET',
url: 'https://www.example.com/bankaccounts/',
data: {bankAccountId:_bankAccountId}
}).done(function (bankAccount) {
var div = document.createElement('div');
div.innerHTML = bankAccount.iban;
place.insertAfter(div);
/* I Still have to ask for the Bank name but I stop my example here*/
});
)(place, partener.bankAccountsId[j]);
}
});
})(div, contracts[i].partenerId);
}
});
return output;
}
代码不会像它那样工作,只是为了看到我使用的原理。我希望有更好的解决方案来在Javascript中使用Rest API,你必须要求嵌套结构。