Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JavaScript to perform a GET request without AJAX

Tags:

javascript

Out of curiosity, I'm wondering about the best (easiest, fastest, shortest, etc; make your pick) way to perform a GET request in JavaScript without using AJAX or any external libraries.

It must work cross-browser and it's not allowed to distort the hosting web page visually or affect it's functionality in any way.

I don't care about headers in the request, just the url-part. I also don't care about the result of the request. I just want the server to do something as a side effect when it receives this request, so firing it is all that matters. If your solution requires the servers to return something in particular, that's ok as well.

I'll post my own suggestion as a possible answer, but I would love it if someone could find a better way!

like image 269
Jakob Avatar asked Dec 20 '10 13:12

Jakob


3 Answers

Have you tried using an Image object? Something like:

var req = new Image();
req.onload = function() {
    // Probably not required if you're only interested in
    // making the request and don't need a callback function
}
req.src = 'http://example.com/foo/bar';
like image 167
Ian Oxley Avatar answered Sep 19 '22 02:09

Ian Oxley


function GET(url) {
  var head = document.getElementsByTagName('head')[0];
  var n = document.createElement('script');
  n.src = url;
  n.type = 'text/javascript';
  n.onload = function() { // this is not really mandatory, but removes the tag when finished.
    head.removeChild(n);
  };
  head.appendChild(n);
}
like image 26
Jakob Avatar answered Sep 18 '22 02:09

Jakob


I would go with Pekka idea and use hidden iframe, the advantage is that no further parsing will be done: for image, the browser will try to parse the result as image, for dynamically creating script tag the browser will try to parse the results as JavaScript code.. iframe is "hit and run", the browser doesn't care what's in there.

Changing your own solution a bit:

function GET(url) {
    var oFrame = document.getElementById("MyAjaxFrame");
    if (!oFrame) {
        oFrame = document.createElement("iframe");
        oFrame.style.display = "none";
        oFrame.id = "MyAjaxFrame";
        document.body.appendChild(oFrame);
    }
    oFrame.src = url;
}
like image 33
Shadow Wizard Hates Omicron Avatar answered Sep 22 '22 02:09

Shadow Wizard Hates Omicron