简体   繁体   中英

Get Solr Response as json via javascript

I need to get the solr query response through java script. I did the following code to get the response. But the response text shows only the empty string. It doesn't retrieve the data from solr. Please guide me the mistake I did. Thank you..

function getSolrResponse() {
    var strURL = "http://localhost:8983/solr/Core1/select";
    var xmlHttpReq = false;
    if (window.XMLHttpRequest) { 
        xmlHttpReq = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
        xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttpReq.open('POST', strURL, true);
    xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlHttpReq.onreadystatechange = function() {
        if (xmlHttpReq.readyState == 4) {
            alert(xmlHttpReq.responseText);
        }
    };
    xmlHttpReq.send("q=*:*&wt=json");
}

Have a look at the Solr's own logs. It will show you both the query string you got and the error messages.

Specifically for here, why are you doing a POST? Start with a GET (easier to debug) and then adapt.

I think the problem is in your last line of code:

xmlHttpReq.send("q=*:*&wt=json");

Effectively, Solr doens't recieve this namve/value pairs with the request, and it simply thinks that your request lacks the query part (the wt=json part is optional). If you instead append it to the request URL, it will return proper JSON. Here's a version of your code, with this modification, which I've tested and works ok:

    function getSolrResponse() {
        var strURL = "http://localhost:8983/solr/DOWNMUSIC/select?q=*:*&wt=json";
        var xmlHttpReq = false;
        if (window.XMLHttpRequest) { 
            xmlHttpReq = new XMLHttpRequest(); 
        } else if (window.ActiveXObject) { 
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlHttpReq.open('POST', strURL, true);
        xmlHttpReq.setRequestHeader('Content-Type', 'application/json');
        xmlHttpReq.onreadystatechange = function() {
            if (xmlHttpReq.readyState == 4) {
                alert(xmlHttpReq.responseText);
            } else {
                //alert("ELSE: "+xmlHttpReq.responseText);
            }
        };
        xmlHttpReq.send();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM