如何在clojurescript中获取查询参数?

时间:2015-09-14 20:12:26

标签: clojurescript reagent secretary

我正在使用秘书和试剂。这是我的代码:

(def view (atom nil))

(defn layout [view]
  [:div @view])

(reagent/render-component [layout view] (.getElementById js/document "message"))

(secretary/set-config! :prefix "")

(secretary/defroute home-path "/" [query-params]
  (timbre/info "Path : /, query params : " query-params)
  (let [warning (:warning query-params)
        success (:success query-params)
        login-failed (:login_failed query-params)]
    (when warning
      (timbre/info "Warning found : " warning)
      (reset! view [:h4 [:span.label.label-warning warning]]))
    (when success
      (timbre/info "Success found : " success)
      (reset! view [:h4 [:span.label.label-info success]]))
    (when login-failed
      (timbre/info "Login failed")
      (reset! view [:h4 [:span.label.label-warning "Login Failed."]]))))

(let [h (History.)]
 (goog.events/listen h EventType.NAVIGATE #(secretary/dispatch! (.-token %)))
 (doto h
  (.setEnabled true)))

忽略:前缀值(我试过“”,“#”并且根本没有设置:前缀)此代码仅适用于以下路由:

http://localhost:8080/login#/?success=SuccessMessage

但它不适用于以下路线:

http://localhost:8080/login?success=SuccessMessage

我实际上想要实现的是解析friend的登录失败,如果失败则会将我重定向到

http://localhost:8080/login?&login_failed=Y&username=someUser

并向用户显示登录失败消息。 我不需要使用秘书,任何可以解析查询参数的东西对我来说都没问题。

困难的方法是解析我可以得到的查询字符串:

(-> js/window .-location .-search)

我相信在某些图书馆已经做得很好。

2 个答案:

答案 0 :(得分:14)

我找到了。使用https://github.com/cemerick/url(适用于clojure和clojurescript),可以做到:

(require '[cemerick.url :as url])
(:query (url/url (-> js/window .-location .-href)))

答案 1 :(得分:0)

来自docs

如果URI包含查询字符串,它将被自动提取到:query-params(用于字符串路由匹配器),并提取到最后一个元素(用于正则表达式匹配器)。

(defroute "/users/:id" [id query-params]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

(defroute #"/users/(\d+)" [id {:keys [query-params]}]
  (js/console.log (str "User: " id))
  (js/console.log (pr-str query-params)))

;; In both instances...
(secretary/dispatch! "/users/10?action=delete")
;; ... will log
;; User: 10
;; "{:action \"delete\"}"