我们可以使用AJAX(异步JavaScript和XML)或fetch API调用api接口数据。
比方说,我们要调用github的API。
使用AJAX:
var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if(this.readyState == 4 && this.status == 200) { //Action to be performed when the document is read; } }; xhr.open("GET", "https://api.github.com/users/user_name",true); xhr.send();
使用fetch:
fetch('https://api.github.com/users/user_name') .then(response => response.json()) .then(data => { // do something with the data });
前端开发人员在调API的时候应该去了解它的请求和响应格式。此外,还应该注意API的限制,例如每小时的最大请求量,以及API的安全性。
提倡使用https协议来传输数据。