api接口指的是應用程序編程接口(Application Programming Interface),是一些預先定義的函數,或指軟件系統不同組成部分銜接的約定。用來提供應用程序與開發人員基于某軟件或硬件得以訪問的一組例程,而又無需訪問原碼,或理解內部工作機制的細節。
function productClickHandler() {
var xhr = new XMLHttpRequest(); // 創建xhr對象
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
var result = JSON.parse(xhr.responseText); // 將字符串轉化為對象,然后才能獲取到返回字符串中的某一個值
console.log(result.totalCount); // 獲取返回字符串中的某一個值
} else {
alert('Request was unsuccessful: ' + xhr.status);
}
}
}
var url = 'http://study.163.com/webDev/couresByCategory.htm?' + "pageNo=1&psize=1&type=10"; // 獲取課程列表,帶參數的get請求
xhr.open('get', url, true); // 開啟一個請求,但還沒有向服務器端發起請求,執行后redayState的值變為1
xhr.send(null); // 向服務器端發起請求,執行后redayState的值變為2
// 補充:當服務器端開始返回請求數據的時候,瀏覽器端接收到這個數據,redayState的值變為3。
// 當瀏覽器端結束請求時,redayState的值變為4,status的值變為200(表示請求成功),responseText變為相應的返回值。
}
然后可以通過getElementById("id")等方法獲取到html元素,再使用.innerHTML將獲取到的值插入html。