简体   繁体   中英

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:

http://<OwnIPadres>:8080/calc/something?var=that

This is my code:

 function httpGet(theUrl)
  {
      alert(theUrl);
        var doc = new XMLHttpRequest();
        doc.onreadystatechange = function() {
            if (doc.readyState == XMLHttpRequest.DONE) {
                alert("text: " + doc.responseText );
                 document.getElementById('ctm').text = doc.responseText;
            }
        }
        doc.open("get", theUrl);
        doc.setRequestHeader("Content-Encoding", "UTF-8");
        doc.send();
  }

The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?

Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.

I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an

Access-Control-Allow-Origin: http://:8080/

in your header (however that will only get you the most modern browsers).

Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

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