Using JavaScript to execute a GET request without AJAX

Out of curiosity, I wonder how to make the best (easiest, fastest, shortest, etc.) for executing a GET request in JavaScript without using AJAX or any external libraries.

It must work with a cross browser, and it cannot distort the web page of the hosting visually or in any way affect its functionality.

I do not need headers in the request, only part of the url. I also don't care about query results. I just want the server to do something as a side effect when it receives this request, so it all matters. If your solution requires the servers to return something in particular, this is normal.

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

+5
source share
3 answers

Have you tried to use the Image object? Sort of:

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';
+7
source
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);
}
+1
source

iframe, , : , script JavaScript. iframe " ", , .

:

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;
}
+1

All Articles