CoffeeScript - Ajax



AJAX 是一種用於建立互動式 Web 應用程式的 Web 開發技術。

  • AJAX 代表 **A**synchronous **Ja**vaScript and **X**ML。它是一種用於建立更好、更快、更互動式 Web 應用程式的新技術,藉助 XML、HTML、CSS 和 JavaScript。

  • Ajax 使用 XHTML 用於內容,CSS 用於表示,以及文件物件模型和 JavaScript 用於動態內容顯示。

  • 傳統的 Web 應用程式使用同步請求在伺服器之間傳輸資訊。這意味著您填寫表單,點選提交,然後被定向到一個包含來自伺服器的新資訊的新頁面。

  • 使用 AJAX,當您點選提交時,JavaScript 將向伺服器發出請求,解釋結果,並更新當前螢幕。從最純粹的意義上說,使用者永遠不會知道任何東西甚至被傳輸到伺服器。

  • XML 通常用作接收伺服器資料的格式,儘管可以使用任何格式,包括純文字。

  • AJAX 是一種獨立於 Web 伺服器軟體的 Web 瀏覽器技術。

  • 客戶端程式在後臺向伺服器請求資訊時,使用者可以繼續使用應用程式。

一般來說,我們使用 jQuery 來處理 Ajax。以下是 Ajax 和 jQuery 的示例

<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		
      <script type = "text/javascript" language = "javascript">
         $(document).ready(function() {
            $("#driver").click(function(event){
               $('#stage').load('/jquery/result.html');
            });
         });
      </script>
   </head>
	
   <body>
	
      <p>Click on the button to load /jquery/result.html file −</p>
		
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
		
   </body>
	
</html>

這裡 `load()` 啟動對指定 URL `/coffeescript/result.html` 檔案的 Ajax 請求。載入此檔案後,所有內容都將填充到 ID 為 `stage` 的 `

` 標籤內。假設我們的 `/jquery/result.html` 檔案只有一行 HTML 程式碼:

<h1>THIS IS RESULT...</h1>

單擊給定的按鈕時,將載入 result.html 檔案。

CoffeeScript 與 Ajax

我們可以使用 CoffeeScript 重寫上面的示例,如下所示。

<html>

   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript"
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src="http://coffeescript.org/extras/coffee-script.js"></script>
        
      <script type="text/coffeescript">
        $(document).ready ->
          $('#driver').click (event) ->
            $('#stage').load '/jquery/result.html'
            return
          return
      </script>
   </head>
	
   <body>
	
      <p>Click on the button to load /jquery/result.html file -</p>
		
      <div id = "stage" style = "background-color:cc0;">
         STAGE
      </div>
		
      <input type = "button" id = "driver" value = "Load Data" />
		
   </body>
	
</html>
廣告