5

我是一个 javascript/web 应用程序新手,正在尝试使用 hunchentoot 和骨干网实现我的第一个 web 应用程序。我尝试的第一件事是了解 model.fetch() 和 model.save() 是如何工作的。

在我看来,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
           ....))))

这旨在处理对应 url 为“/dataset”的模型的获取/保存。提取工作正常,但我对 save() 感到非常困惑。我看到了由 easy-handler 触发和处理的“post”请求,但该请求似乎只有一个有意义的标头,我找不到隐藏在请求中的实际 json 对象。所以我的问题是

  1. 如何从 model.save() 触发的 post 请求中获取 json 对象,以便以后可以使用 json 库(例如,jsown)来解析它?
  2. hunchentoot 应该回复什么才能让客户端知道“保存”成功了?

我在 hunchentoot 中尝试了“post-parameters”函数,它返回 nil,并没有看到很多人通过谷歌搜索使用 hunchentoot+backbone.js。如果您可以将我引导到一些有助于理解backbone.js save() 工作原理的文章/博客文章,这也很有帮助。

非常感谢您的耐心等待!

4

1 回答 1

9

感谢 wvxvw 的评论,我找到了这个问题的解决方案。对象可以通过调用来检索hunchentoot:raw-post-data。更详细地说,我们首先调用(hunchentoot:raw-post-data :force-text t)以字符串形式获取帖子数据,然后将其提供给jsown:parse. 一个完整的easy-handler如下所示:

(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.

希望这可以帮助其他有同样困惑的人。

于 2012-10-07T04:22:35.203 回答