使用hunchentoot解析Backbone.js中model.save()发送的post请求



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

在我看来,model.fetch()会触发一个"GET"请求,而model.save()会引发一个"POST"请求。因此,我在hutchentoot中写了一个简单的处理程序如下:

(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"的模型的获取/保存而设计的。fetch操作很好,但我被save()弄糊涂了。我看到easy处理程序触发并处理了"post"请求,但该请求似乎只有一个有意义的头,我找不到隐藏在请求中的实际json对象。所以我的问题是

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

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

非常感谢你的耐心!

感谢wvxvw的评论,我找到了这个问题的解决方案。json对象可以通过调用hunchentoot:raw-post-data来检索。更详细地说,我们首先调用(hunchentoot:raw-post-data :force-text t)以获得字符串形式的post数据,然后将其提供给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.

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

最新更新