Skip to content

Instantly share code, notes, and snippets.

@timgluz
Created May 27, 2013 20:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timgluz/5658889 to your computer and use it in GitHub Desktop.
Save timgluz/5658889 to your computer and use it in GitHub Desktop.
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