简体   繁体   English

使用JavaScript在没有AJAX的情况下执行GET请求

[英]Using JavaScript to perform a GET request without AJAX

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. 出于好奇,我想知道最好的(最简单,最快,最短等;做出选择)方式在JavaScript中执行GET请求而不使用AJAX或任何外部库。

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. 我不关心请求中的标题,只关注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? 您是否尝试过使用Image对象? 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. 我会使用Pekka的想法并使用隐藏的iframe,优点是不会进行进一步的解析:对于图像,浏览器将尝试将结果解析为图像,为了动态创建script标记,浏览器将尝试将结果解析为JavaScript代码.. iframe是“点击并运行”,浏览器并不关心那里有什么。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM