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

时间:2023-03-08 22:33:28
跨域请求获取Solr json检索结果并高亮显示

  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>