【问题标题】:Implementing an ajax call in clojurescript在 clojurescript 中实现 ajax 调用
【发布时间】:2012-01-23 04:40:07
【问题描述】:

我是 clojurescript 的新手,想通过纯粹在 clojurescript 中实现以前编写的应用程序来进行更深入的研究,但在实现 ajax 调用方面不知所措。谁能给我指一个在线示例或提供一两个代码 sn-p 吗?

【问题讨论】:

    标签: ajax jsonp clojurescript


    【解决方案1】:

    2016 年 1 月 22 日更新

    虽然它仍然有效,但最初的答案是在普遍缺乏具有超过 1 个贡献者的 ClojureScript 解决方案的时候。与其直接利用 XhrIo,不如考虑使用维护良好、功能丰富的解决方案,而不是像 cljs-ajax 那样包装它,如下面的 Mikhail D 建议的那样!


    好的,鉴于 Clojurescript 利用了 Google 的 Closure JavaScript 库,快速搜索 Closure 文档发现 xhrIo 作为生成 AJAX 调用的正确方法:

    Example using Closure's Asynchronous XMLHttpRequests with XhrIo

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

    快速查看 Clojurescript 源代码发现了以下功能:

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

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

    因此,与此类似的东西应该有预期的结果:

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

    对于 JSONP,您可以使用 goog.net.Jsonp 执行类似的操作。详情见链接:

    JSONP Closure API

    希望有人觉得这很有帮助!

    【讨论】:

    • 我有点困惑:为什么(.send xhr url myCallback) 有效?据我所知,xhr-connection 是一个返回新的goog.net.XhrIo 的函数,那么为什么.send 可以使用它呢?
    • goog.net.XhrIo 上的尾随点。使其等同于new goog.net.XhrIo()
    【解决方案2】:

    另一个可行的选择可能是https://github.com/JulianBirch/cljs-ajax

    由于它是为 ClojureScript 设计的,因此语法看起来更清晰、更简单。它还支持很多开箱即用的功能(例如:transitednjson 格式)。

    自述文件中的一些示例:

    (ns foo
      (:require [ajax.core :refer [GET POST]]))
    
    ...
    
    (GET "/hello" {:handler handler
                   :error-handler error-handler})
    
    (POST "/send-message"
        {:params {:message "Hello World"
                  :user    "Bob"}
         :handler handler
         :error-handler error-handler})
    

    【讨论】:

      【解决方案3】:

      我的做法略有不同。我不知道为什么马克在他的回答中建议的方式对我不起作用。希望这也有用。

      我直接使用了goog.net.XhrIo,而不是xhr-connection 包装器。

      (defn callback [reply]
          (let [v (js->clj (.getResponseJson (.-target reply)))] ;v is a Clojure data structure
              (your-function-here v)))
      
      (.send goog.net.XhrIo url callback)
      

      我可以看到的主要区别是我使用.-target 来获取JSON 对象的属性,而不是调用target

      值得注意的是,v 中从 JSON 对象创建的映射由字符串而非关键字作为键。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多