1

I have a simple CGI script that would generate plain text content on demand. For example, http://1.2.3.4/hello.cgi?name=Joe would return Hello Joe!.

How can I read this into a string in Javascript?

name     = "Joe";
url      = "http://1.2.3.4/hello.cgi?name=" + name;
greeting = loadThis(url);

I'm new to Javascript, so even naive approach (i.e. no need to URL escape...) will be helpful for me :)

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
  • you might want to take a look at [this post](http://stackoverflow.com/q/432144/575527) – Joseph Apr 25 '12 at 09:13
  • 1
    And keep in mind same-origin policy. For different origins you'd have to use sth. like [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) or [JSONP](http://en.wikipedia.org/wiki/JSONP). – Makkes Apr 25 '12 at 09:29
  • @Joseph I'm currently trying to make sense out of JQuery :) However, I really just need that single trivial thing and not even a bit more, and I prefer the fastest way possible, i.e. using nothing more than plain JS. I was hoping this would be easy and someone could just type it here instantly from head :) – Alois Mahdal Apr 25 '12 at 09:29

1 Answers1

1

Based on this FAQ on JavaScriper.net, I have found solution that works for me. However, the called script must be on the same machine as the caller, otherwise I get security errors from browsers.

Apparently this is what @Makkes mentioned. However, I'm perfectly happy with having the hello.cgi on the same machine for now.

Here is the code:

function loadThis(localuri) {
    var oRequest = new XMLHttpRequest();

    var sURL = 'http://'
        + self.location.hostname
        + localuri;

    oRequest.open('GET',sURL,false);
    oRequest.setRequestHeader('User-Agent',navigator.userAgent);
    oRequest.send(null);

    if (oRequest.status==200) return(oRequest.responseText);
    else alert('Error executing XMLHttpRequest call!');
}

name        = "Joe";
localuri    = "/hello.cgi?name=" + name;
greeting    = loadThis(localuri);

(Of course, this would not handle names with spaces or special characters correctly, but that's another story.)

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69