Last Updated: February 25, 2016
·
2.798K
· timgluz

Ajax with Clojurescript browser.net library.

There's couple of Clojurescript Ajax libraries, but i want to keep project dependencies as minimal as possible and it's the reason i picked Clojurescript's core library to do ajax request.

Clojure.browser.net is just simple wrapper around Google's Closure net library. Whenever you want know more info about this ajax client, you should check out official XHRio documentation..

(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"})))

And here is list of supported events:

  • :complete goog.net.EventType.COMPLETE
  • :success goog.net.EventType.SUCCESS
  • :error goog.net.EventType.ERROR
  • :timeout goog.net.EventType.TIMEOUT
  • :ready goog.net.EventType.READY}

Source code on gist

2 Responses
Add your response

Just another library, but I've been using this one:

https://github.com/yogthos/cljs-ajax

Just wraps the Closure library stuff too. Handles EDN etc...

over 1 year ago ·

@rodnaph , thanks for your comment; Yes, cljs-ajax is neat framework; and i like it tries to implement ring-like interface as clj-http has. But i drop it for very simple reason - i'm writing app for firefox OS and i want to keep external dependencies as low as possible;

over 1 year ago ·