2016-11-14 125 views
2

我想在ClojureScript中實現AJAX POST。ClojureScript AJAX POST發送json數據

以下是我使用

(defn handler [response] 
    (.log js/console (str response))) 

(defn test-post [name email] 
    (let [data {:name name :email email}] 
    (POST "http://localhost:5000/Add/" 
    { 
    :format {"Accept" :json} 
    :body (.stringify js/JSON (clj->js data)) 
    :handler handler 
    :error-handler (fn [r] (prn r)) 
    :response-format {"Content-Type" "application/json;charset=utf-8"} 
    } 
    ))) 

當我稱Post方法的代碼。在表單上提交?此外,發佈請求正在擊中url,但json數據不存在。

+0

[訪問控制 - 允許來源](https://www.w3.org/TR/access-control/#access-control-allow-origin-response-header)是**響應**標題不是請求標頭,它在請求中是無用的。 – Marcs

+0

'POST'從哪裏來?大概來自一些圖書館? – Dan

+0

POST是cljs-ajax庫的一部分 – zain

回答

2

我假設您使用cljs-ajax發送數據。

你真正需要的是這樣的:

(let [data {:name name :email email}] 
(POST "/Add" 
    {:format :json 
    :params data 
    :handler handler 
    :error-handler (fn [r] (prn r))}))) 

你可以只通過一個簡單的Clojure的對象作爲參數,可以只設置:json數據格式(默認爲:transit)。

第二個問題相當開放,取決於您的設置。我認爲最簡單的方法是使用reagent,這裏有一個很好的example發送表單數據。

+0

我想我錯過了:header {「Accept」「application/json」:content-type「application/json; charset = utf-8」} – zain