2012-10-06 48 views
4

我是一個javascript/web應用程序新手,並嘗試使用hunchentoot和backbone.js實現我的第一個Web應用程序。我正在嘗試的第一件事是瞭解model.fetch()和model.save()如何工作。使用hunchentoot解析backbone.js中model.save()發送的post請求

在我看來,model.fetch()激發了「GET」請求,而model.save()激發了「POST」請求。因此,我寫了一個hunchentoot易於處理程序如下:

(hunchentoot:define-easy-handler (dataset-handler :uri "/dataset")() 
    (setf (hunchentoot:content-type*) "text/html") 

    ;; get the request type, canbe :get or :post 
    (let ((request-type (hunchentoot:request-method hunchentoot:*request*))) 
    (cond ((eq request-type :get) 
      (dataset-update) 
      ;; return the json boject constructed by jsown 
      (jsown:to-json (list :obj 
           (cons "length" *dataset-size*) 
           (cons "folder" *dataset-folder*) 
           (cons "list" *dataset-list*)))) 
      ((eq request-type :post) 
      ;; have no idea on what to do here 
      ....)))) 

這是專門用來處理抓取/保存其對應的網址爲「/數據集」的典範。抓取工作正常,但我真的很困惑的保存()。我看到了簡單處理程序觸發和處理的「發佈」請求,但該請求似乎只有一個有意義的標題,我找不到隱藏在請求中的實際json對象。所以我的問題是

  1. 我怎樣才能得到json對象從model.save()發射的發佈請求中,以便後來的json庫(例如jsown)可以用來解析它?
  2. hunchentoot回覆爲了讓客戶知道「保存」成功了嗎?

我試過hunchentoot中的「​​後參數」函數,它返回零,並沒有看到許多人使用hunchentoot + backbone.js通過谷歌搜索。如果你能指導我閱讀一些有助於理解backbone.js save()如何工作的文章/博客文章,這也很有幫助。

非常感謝您的耐心等待!

+0

謝謝!我認爲'raw-post-data'是正確的答案。在問這個問題之前,我實際上已經嘗試了這個方法,但是餵了一個錯誤的論點。 – BreakDS

回答

6

感謝wvxvw的評論,我找到了解決這個問題的方法。通過調用hunchentoot:raw-post-data可以檢索到對象。爲了更加詳細,我們首先撥打(hunchentoot:raw-post-data :force-text t)來獲取帖子數據作爲字符串,然後將其提供給jsown:parse。一個完整的簡易處理程序如下所示:

(hunchentoot:define-easy-handler (some-handler :uri "/some")() 
    (setf (hunchentoot:content-type*) "text/html") 
    (let ((request-type (hunchentoot:request-method hunchentoot:*request*))) 
    (cond ((eq request-type :get) ...);; handle get request 
      ((eq request-type :post) 
      (let* ((data-string (hunchentoot:raw-post-data :force-text t)) 
        (json-obj (jsown:parse data-string))) ;; use jsown to parse the string 
       .... ;; play with json-obj 
       data-string))))) ;; return the original post data string, so that the save() in backbone.js will be notified about the success. 

希望這可以幫助其他人有同樣的困惑。