Skip to Content
JavaScript 設計模式
book

JavaScript 設計模式

by Stoyan Stefanov
March 2012
Intermediate to advanced
244 pages
4h 42m
Chinese
GoTop Information, Inc.
Content preview from JavaScript 設計模式
198
   
第八章
遠端操作
現代的網頁應用通常都會使用遠端操作的 script 來和伺服器通訊,而不再重新載入頁面。
這麼做允許了回應性更佳、更類似桌面應用的網頁應用程式。我們來看看用 JavaScript
伺服器通訊的幾種方法:[190]
XMLHttpRequest
XMLHttpRequest
是一個特殊的物件,而且是個建構式,在大多數現代的瀏覽器中都可以
使用。它讓你可以在 JavaScript 送出一個 HTTP 請求,發送請求需要三個步驟:
1. 建立一個
XMLHttpRequest
物件,通常簡稱為 XHR
2. 提供一個回呼函式,當請求物件的狀態改變時可以獲得通知。
3. 送出請求。
第一個步驟很簡單:
但在 IE7 之前的版本,XHR 功能是實作為一個 ActiveX 物件,所以在這裡需要處理
特例。
第二步是對
readystatechange
事件提供回呼:
最後一步是發送請求,這要使用兩個方法,
open()
send()
open()
方法會設定好
HTTP 請求的方式(例如 GET POST),和 URL
send()
方法則傳遞任何要 POST
資料,或者只是個空字串,如果是用 GET 的話。另外,
open()
的最後一個參數指定了該
請求是否為非同步(asynchronous)。非同步的意思是,瀏覽器不會停止下來等待回應。
這絕對是更好的使用者體驗,所以除非有強烈的反對理由,否則非同步的參數應該總是傳
true
下面是一次完 整的工
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

JavaScript 之美

JavaScript 之美

Anton Kovalyov
重構 JavaScript

重構 JavaScript

Evan Burchard

Publisher Resources

ISBN: 9789862764190