Clojure:如何在Clojure / Compojure中使用Jquery实现搜索建议功能

时间:2017-03-24 21:30:28

标签: jquery ajax clojure compojure

我一直在与如何使用jquery在compojure中创建搜索建议框或自动完成框进行斗争,这就是我所拥有的但仍然无法正常工作

在我的路线中。我在下面,我可以看到我的list作为get-client-list的输出 输出类似于{:id 2, :name "foobar"}

(defn get-list! [{:keys [params]}]
  (log/infof "Pulling client list from db" params)
  (let [list (into {} (db/get-client-list params))]

    ;;list is like hugsql
    (log/infof "List of names -> [%s]" list)
    (if (empty? list)
      (log/errorf "No record found [%s]" list)
      (do
        (log/infof "The list is ->[%s]" list)

         ;; seems am missing something here, dont know
         ;;code for readlist.html is still far below
        (layout/render "readlist.html" (:records list))))))


(defn about-page [{:keys [flash]}]
   (layout/render "home.html"
     (merge nil (select-keys flash [:name :amount :value :er :errors]))))


(defroutes home-routes
   (GET "/getinfo" {:keys [headers params body] :as request}
         (do
           (if (empty? (:user (:session request)))
             (do
               (log/info "Unauthorised attempt to /getinfo URL:" request)
               (response/found "/"))
             (about-page request))))
   (POST "/getinfo" request
           (if (empty? (:user (:session request)))
             (do
               (log/info "Unauthorised attempt to /getinfo URL:" request)
               (response/found "/"))
             (msg! request)))

   (GET "/clientlist" request (get-list! request)))

我的home.html

<div class="col-sm-6">
            <p>
                Name:
                <input class="form-control"
                       id="search-box"
                       type="text"
                       name="clientname"
                       value="{{name}}" />
            </p>

            <div id="suggestion-box"></div>
            {% if errors.name %}
            <div class="alert alert-danger">{{errors.name|join}}</div>
            {% endif %}
        </div>

        <div class="col-sm-6">
            <p>
                Amount(in figures):
                <input class="form-control"
                       type="number"
                       name="amount"
                       value="{{amount}}" />
            </p>
            {% if errors.amount %}
            <div class="alert alert-danger">{{errors.amount|join}}</div>
            {% endif %}
        </div>

然后在我的base.html中, 我把这个脚本放在<head>那里

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
  <script>
      $(document).ready(function(){
          $("#search-box").keyup(function(){
              $.ajax({
                  type: "GET",

                  //calling this URL in route.home
                  // why are you not working?
                  url: "/clientlist",
                  data:'keyword='+$(this).val(),
                  beforeSend: function(){
                      $("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
                  },
                  success: function(data){
                      $("#suggestion-box").show();
                      $("#suggestion-box").html(data);
                      $("#search-box").css("background","#FFF");
                  }
              });
          });
      });

      function selectList(val) {
          $("#search-box").val(val);
          $("#suggestion-box").hide();
      }
  </script>

readlist.html代码位于

之下
{% for item in records %}
 <li onClick="selectList('{{item.name|join}}');">
  {{item.name|join}}
</li>
{% endfor %}

请协助,花了好几个小时试图搞清楚。 感谢

1 个答案:

答案 0 :(得分:0)

从您的代码中,我想问题是该建议没有出现,这意味着/clientlist没有做到它应该做的事情。 您的.js脚本似乎很好,所以问题似乎是/clientlist

试试这个,它的粗糙但是会起作用,你可以通过构建它来简化它

(defn process-url-encoded
 "parses the url sent from the .js function"
  [req]
  (let [input (or (:query-string req) (:input-string req))]
    (let [input-vec (apply hash-map (str/split input #"[&=]"))]
      (walk/keywordize-keys input-vec))))


(defn get-list! [req]
  (log/infof "Request sent from .js function")
  (try
    (let [{keyword     :keyword} (process-url-encoded req)
          keywd (str "%" keyword "%")
          param (hash-map :name-like keywd)
          list (into {} (db/get-client-list param))]
          (log/infof "The list is -> %s" list)
          (layout/render "readlist.html" {:record list}))
    (catch Exception e
      (log/errorf "No value supplied -> %s" (.getMessage e))
      (layout/render "readlist.html" {:record {}}))))

然后你的readlist.html应该有这个

<ul id="need-to-style-this-section">

    <li onClick="selectList('{{record.name}}');">
         <!-- name should be your database column name-->
        {{record.name}}
    </li>
</ul>

另外,由于你使用的是clojure模板,它可能是基于hugsql语法的,所以这应该是合适的

-- :name get-client-list :? :*
-- :doc GETS client list
SELECT name FROM table-name
WHERE name LIKE :name-like
ORDER BY name ASC

玩得开心!