开发者

Using JavaScript to perform a GET request without AJAX

开发者 https://www.devze.com 2023-01-31 16:32 出处:网络
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

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!


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';


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);
}


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消