Implementing an ajax call in clojurescript

后端 未结 3 1542
广开言路
广开言路 2021-02-05 10:03

I\'m new to clojurescript and would like to do a deeper dive by implementing a previously written application purely in clojurescript, but am at a loss with respect to to implem

3条回答
  •  太阳男子
    2021-02-05 10:37

    January 22, 2016 update

    Although it still works, the original answer is from a time when there was a general lack of ClojureScript solutions with more than 1 contributor. Rather than leveraging XhrIo directly, definitely consider using a well-maintained, feature-rich solution that wrappers it instead like cljs-ajax, as suggested by Mikhail D below!


    Okay, So given that Clojurescript leverages Google's Closure JavaScript library, a quick search of the Closure Documentation yielded xhrIo as the proper method for generating AJAX calls:

    Example using Closure's Asynchronous XMLHttpRequests with XhrIo

    goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content,
         opt_headers, opt_timeoutInterval)
    

    A quick review of the Clojurescript source revealed the following function:

    From src/cljs/clojure/browser/net.cljs in clojure / clojurescript

    (defn xhr-connection
      "Returns an XhrIo connection"
      []
      (goog.net.XhrIo.))
    

    So something along the lines of this should have the intended results:

    (def xhr xhr-connection)
    
    (defn myCallback [replyValue] 
      ... Do Something with replyValue
      ... for example: (someJsonFunc (.getResponseJson (.target replyValue))))
    
    (defn ajax-json [url]
       (.send xhr url myCallback))
    

    For JSONP, you can do something similar using the goog.net.Jsonp. See the link for details:

    JSONP Closure API

    Hope someone finds this helpful!

提交回复
热议问题