且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跨域请求获取Solr json检索结果并高亮显示

更新时间:2022-06-28 09:50:28

  Solr提供了json格式的检索结果,然而在跨域的情况下如何调用呢?我们可以利用jquery提供的jsonp的方式获取Solr检索结果。

<script type="text/javascript" src="./resources/js/jquery-1.8.2.min.js"></script>
    <input type="text" size="50" value="" id="keyword" name="keyword" />
    <input type="button" value="搜索" id="search" />
    <div id="result"></div>
    <script type="text/javascript">
        $("#search").click(function() {
            var keyword = $("#keyword").val();
            var solrServer = "http://localhost:8080/solr/solrfirstcore/select";
            $.ajax({
                type : "get",
                url : solrServer,
                data : {
                    wt : "json",
                    q : "search_item:" + keyword,
                    indent : true,
                    "json.wrf" : 'callback',
                    "hl" : "true",
                    "hl.fl" : "title, summary",
                    "hl.simple.pre" : "<font color=\"red\">",
                    "hl.simple.post" : "</font>",
                    "start":"0",
                    "rows":"20"
                },
                dataType : "jsonp",
                //jsonp : "callback",
                jsonpCallback : "callback",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名
                error : function() {
                    $("#result").html("<font color=\"red\">没有您要查询的结果。</font>");
                }
            });
        });

        function callback(data) {
            var responseHeader = data.responseHeader;
            var response = data.response;
            var highlighting = data.highlighting;
            var docs = response.docs;
            var result = new Array();
            result.push("结果数:" + response.numFound + "条,耗时:"
                    + responseHeader.QTime / 1000 + "");
            var hlString = "";
            for ( var index in docs) {
                var doc = docs[index];
                var docid = doc.id;
                hl_string = "【ID】:" + doc.id;
                var hdoc = highlighting[docid];
                var title = doc.title;
                var summary = doc.summary;
                if(hdoc.title){
                    title = hdoc.title;
                }
                if(hdoc.summary){
                    summary = hdoc.summary;
                }
                hl_string += ", 【标题】:" + title + ", 【描述】:" + summary;
                
                result.push("------------------------------------------------------------");
                result.push(hl_string);
            }

            $("#result").html("</br>" + result.join("</br>"));
        }
    </script>