CherryPy - Ajax的使用



直到2005年,所有Web應用程式都遵循的模式是每個頁面管理一個HTTP請求。從一個頁面導航到另一個頁面需要載入整個頁面。這將大大降低效能。

因此,出現了富客戶端應用程式,它們會嵌入AJAX、XML和JSON。

AJAX

非同步 JavaScript 和 XML(AJAX)是一種建立快速且動態網頁的技術。AJAX允許網頁透過在後臺與伺服器交換少量資料來非同步更新。這意味著可以更新網頁的一部分,而無需重新載入整個頁面。

Google Maps、Gmail、YouTube和Facebook是AJAX應用程式的一些示例。

Ajax基於使用JavaScript傳送HTTP請求的想法;更具體地說,AJAX依賴於XMLHttpRequest物件及其API來執行這些操作。

JSON

JSON是一種以JavaScript應用程式可以評估它們並將它們轉換為以後可以操作的JavaScript物件的方式來攜帶序列化JavaScript物件的方式。

例如,當用戶請求伺服器以JSON格式格式化的專輯物件時,伺服器將返回以下輸出:

{'description': 'This is a simple demo album for you to test', 'author': ‘xyz’}

現在資料是一個JavaScript關聯陣列,並且可以透過以下方式訪問description欄位:

data ['description'];

將AJAX應用於應用程式

考慮包含名為“media”的資料夾的應用程式,其中包含index.html和Jquery外掛,以及一個包含AJAX實現的檔案。讓我們將檔案命名為“ajax_app.py”

ajax_app.py

import cherrypy
import webbrowser
import os
import simplejson
import sys

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")

class AjaxApp(object):
   @cherrypy.expose
   def index(self):
      return open(os.path.join(MEDIA_DIR, u'index.html'))

   @cherrypy.expose
   def submit(self, name):
      cherrypy.response.headers['Content-Type'] = 'application/json'
      return simplejson.dumps(dict(title="Hello, %s" % name))
		
config = {'/media':
   {'tools.staticdir.on': True,
   'tools.staticdir.dir': MEDIA_DIR,}
}
			
def open_page():
webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(AjaxApp(), '/', config=config)
cherrypy.engine.start()

類“AjaxApp”重定向到“index.html”的網頁,該網頁包含在media資料夾中。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   " http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	
<html xmlns = "http://www.w3.org/1999/xhtml" lang = "en" xml:lang = "en">
   <head>
      <title>AJAX with jQuery and cherrypy</title>
      <meta http-equiv = " Content-Type" content = " text/html; charset = utf-8" />
      <script type = " text/javascript" src = " /media/jquery-1.4.2.min.js"></script>
		
      <script type = " text/javascript">
         $(function() {
         
            // When the testform is submitted...
            $("#formtest").submit(function() {
         
               // post the form values via AJAX...
               $.post('/submit', {name: $("#name").val()}, function(data) {
         
                  // and set the title with the result
                  $("#title").html(data['title']) ;
               });
               return false ;
            });
         });
      </script>
		
   </head>
	
   <body>
      <h1 id = "title">What's your name?</h1>
      <form id = " formtest" action = " #" method = " post">
         <p>
            <label for = " name">Name:</label>
            <input type = " text" id = "name" /> <br />
            <input type = " submit" value = " Set" />
         </p>
      </form>
   </body>
	
</html>

AJAX函式包含在<script>標籤中。

輸出

以上程式碼將產生以下輸出:

Ajax Output

使用者提交值後,將實現AJAX功能,螢幕將重定向到如下所示的表單:

Output Screen
廣告

© . All rights reserved.