Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple ajax with closure.browser.net
(ns foxyeye.search
(:use-macros [dommy.macros :only [sel sel1]])
(:require [clojure.browser.event :as gevent]
[clojure.browser.net :as net]
[dommy.core :as dommy]
[clojure.string :as string]))
;; example template
(deftemplate search-result-item-template [item]
[:li
[:div.icon
[:img {:src (format "/img/languages/%s.png"
(string/lower-case (aget item "language")))}]]
[:div.data
[:h4 (aget item "name")
[:small (str "(" (aget item "prod_key") ")")]]
[:p [:strong "Latest version:"]
(aget item "version")]]])
;; callback for successful response - that parses json and renders template
(defn search-success [ev]
(let [response (.getResponseJson (.-target ev))]
(.log js/console "Rendering search results")
(dommy/append! (sel1 :#search-result-list)
(map #(search-result-item-template %1)
(aget response "results")))))
;; registers callbacks and makes request
(defn fetch-search-results [q]
(let [api-url "http://127.0.0.1:8080/search/query"
;; initialize ajax client
xhr (gnet/xhr-connection.)]
;; register handlers
(gevent/listen xhr :error #(.log js/console Error" %1))
(gevent/listen xhr :success search-success)
;; make request
(gnet/transmit xhr api-url "GET" {:q "json"})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment