0

I'm using an Thesaurus API. The website says: The list of synonyms related to a word can be retrieved by sending a HTTP GET message to the endpoint but a tab of the site finds a synonym with the following code:

var s = document.createElement("script"); 
s.src = "http://thesaurus.altervista.org/service.php?word=peace&language=en_US&output=json&key=test_only&callback=process"; 
document.getElementsByTagName("head")[0].appendChild(s); 

It then defines the callback function 'process' that is part of the url above and process is passed a "result" parameter with the result. I'm unused to making an HTTP GET request in this manner and simply curious about it. I've only ever seen requests made using XMLHttpRequest. (New to programming).

My main question is whether you could get the same result with XMLHttpRequest, something like the following. When I try it doesn't work. Any information about how the above code is making an HTTP request would be much appreciated too.

var req = new XMLHttpRequest();
req.addEventListener("load", reqListener});
req.open("GET", url, true); //where url is same as above but without callback part
req.send();
function reqListener() {
   alert(req.statusCode);
} 
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
J. Doe
  • 33
  • 1
  • 5
  • Plug `http://thesaurus.altervista.org/service.php?word=peace&language=en_US&output=json&key=test_only&callback=process` into the browser address bar, and see what it returns. – Robert Harvey Jul 27 '16 at 06:09
  • As an aside, your second example doesn't appear to be valid Javascript (it contains an extra brace). – Robert Harvey Jul 27 '16 at 06:11
  • The second method doesn't work because of the same-origin restriction of XMLHttpRequest. The first method is [JSONP](https://en.wikipedia.org/wiki/JSONP) – Barmar Jul 27 '16 at 06:16
  • The API allows you to use JSONP, and XMLHttpRequest just like in your example. The documentation was probably written before CORS was widely supported by main stream web browsers. Your XMLHttpRequest works because their server is returning an "Access-Control-Allow-Origin: *" header with it's response. If this header wasn't there, the XMLHttpRequest method in your example would fail due to cross origin policy security. – Mark At Ramp51 Jul 27 '16 at 06:20

0 Answers0