Microsoft™ 和 Internet Explorer 使用了一個名為 XMLHttp 的對象,而不是 XMLHttpRequest 對象,而 Mozilla、Opera、Safari 和 大部分非 Microsoft 瀏覽器都使用的是后者。為了簡單性起見,我將這兩個對象都簡單地稱為 XMLHttpRequest。這既符合我們在 Web 上看到的情況,又符合 Microsoft 在 Internet Explorer 7.0 中使用 XMLHttpRequest 作為請求對象的意圖。(有關這個問題的更多內(nèi)容,請參見 第 2 部分。)
function updatePage() { if (request.readyState == 4) { var newTotal = request.responseText; var totalSoldEl = document.getElementById("total-sold"); var netProfitEl = document.getElementById("net-profit"); replaceText(totalSoldEl, newTotal);
/* 圖 out the new net profit */ var boardCostEl = document.getElementById("board-cost"); var boardCost = getText(boardCostEl); var manCostEl = document.getElementById("man-cost"); var manCost = getText(manCostEl); var profitPerBoard = boardCost - manCost; var netProfit = profitPerBoard * newTotal;
/* Update the net profit on the sales form */ netProfit = Math.round(netProfit * 100) / 100; replaceText(netProfitEl, netProfit); }
function updatePage() { // Output the current ready state alert("updatePage() called with ready state of " + request.readyState + " and a response text of ‘" + request.responseText + "‘"); }
現(xiàn)在在瀏覽器中打開 Web 應用程序,并激活您的請求。要更好地看到這段代碼的效果,請使用 Firefox 或 Internet Explorer,因為這兩個瀏覽器都可以報告出請求過程中所有可能的就緒狀態(tài)。例如在就緒狀態(tài) 2 中,就沒有定義 responseText (請參見 圖 3);如果 JavaScript 控制臺也已經(jīng)打開了,您就會看到一個錯誤。