Chapter 10. Integration with Clojure
ClojureScript, as we have seen, is targeted primarily at web browsers. Although this makes it possible to design complete applications that run in a browser, it is even more powerful when combined with a web server running Clojure on the JVM. Clojure’s literal data structures provide a rich data format for communication between a client and server, and with a little care you can even share code between the two languages.
AJAX
In spite of its original definition, Asynchronous JavaScript and
XML, AJAX has become a catch-all term for rich client
applications running in web browsers, communicating with a web server. The
Google Closure Library provides the goog.net.XhrIo
class to
support asynchronous HTTP requests to a server across many different
browser implementations.
Here is a simple example function that performs an HTTP POST request to a server:
(ns example (:require [goog.net.XhrIo :as xhr])) (defn receiver [event] (let [response (.-target event)] (.write js/document (.getResponseText response)))) (defn post [url content] (xhr/send url receiver "POST" content))
The goog.net.XhrIo/send
function takes a URL, a
callback function, a method name, and an optional request body. When the
server responds to the request, it will invoke the callback function on an
object from which you can retrieve the status code, headers, and response
body sent by the server.
The goog.net.XhrIo
class and the associated
goog.net.XhrManager
class provide many more options ...
Get ClojureScript: Up and Running now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.