How can I request a url using AJAX

2019-05-24 09:47发布

问题:

I am quite new in this area. I need to find out how to make a request to my solr server using Ajax How can I give a url(my solr server's url) in request Any body know how to deal with this? How can i make a request to the below mentioned url

http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on

See here: Corrected the Code Snippet as below

function getProductIds() {
    var xmlhttp;
    if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
    else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
        else alert('no response');
        var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
        xmlhttp.open("GET", ajaxURL, true);
        xmlhttp.send();
    }

This is my code, it always showing "no response"
Thanks.

回答1:

You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below

var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);

after reading your question clearly it seemed it is a static URL hence you can do below

var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);

Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.



回答2:

I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).

In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.

I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.

Ways to circumvent the policy (I haven't had time to study this too much yet)



回答3:

$.ajax({
   url: "url path",
   context: document.body
   }).done(function(data) {
      alert(data);
});

This one also will work.