2

我正在构建我的第一个 Web 应用程序,当用户使用表单时,我很难访问表单的各个字段submit。这是我所拥有的:

(defroutes app
  (GET "/" [] homepage)
  (POST "/city" request display-city)
  (route/resources "/")
  (route/not-found "Not Found"))


(defn display-city [request]
  (html5
     [:div {:class "the-city"}
      [:h2 "ALL ABOUT YOUR CITY"]
      [:ul
       [:li "Your city is " (str request) "! That's all"]]]))

;; and here's the hiccup form:
   [:form {:action "/city" :method "post"}
    (anti-forgery-field)
    [:p "Enter your home address"]
    [:div
     [:label {:for "street-field"} "Street:"]
     [:input {:id "street-field"
              :type "text"
              :name "street"}]]
    [:div
     [:label {:for "city-field"} "City:"]
     [:input {:id "city-field"
              :type "text"
              :name "city"}]
    [:div
     [:label {:for "state-field"} "State:"]
     [:input {:id "state-field"
              :type "text"
              :name "state"}]
     [:label {:for "zip-field"} "ZIP:"]
     [:input {:id "zip-field"
              :type "text"
              :name "zip"
              :size "10"}]]
    [:div.button
     [:button {:type "submit"} "Submit"]]]])

;; 当我运行上面的代码时,我可以看到通过 提交的整个表单,(str request)看起来像是一个 Clojure 映射。但我不知道如何提取单个“key/vals”(从那个地址表单中,我想提取城市),或者如何以我可以使用的方式存储这些结果。有任何想法吗?

这是一个超级基本的/city页面,我试图在构建更大的东西之前运行它以了解事物是如何工作的。谢谢!

4

1 回答 1

4

在您的request地图中,应该有一个:form-params带有已发布的键/值对映射的键。以下是如何获取个人价值的方法:

(get-in request [:form-params :city])

或者您可以解构:form-params映射以一次绑定多个值:

(let [{:keys [city state zip]} (:form-params request)]
  (format "%s, %s %s" city state zip))
于 2018-05-08T10:50:43.107 回答