今天在寫項目的時候,Ajax請求回調函數checkComplete調用一次執行多次導緻資料渲染了好幾遍。然後debug找了好久問題,代碼如下
req = new XMLHttpRequest();
if (req) {
//采用POST方式,異步傳輸
req.open("post", url, true);
//POST方式,必須加入如下頭資訊設定
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.onreadystatechange = checkComplete;
var data = "&id=" + studio;
req.send(data);
}
後來發現onreadystatechange是請求狀态改變就會調用checkComplete()方法,然後将代碼改成下面這樣就好了。
req.onreadystatechange = function () {
if (req.status === 200 && req.readyState === 4) {
checkComplete()
}
};