简体   繁体   English

如何获取xmlhttp请求(AJAX)的URL

[英]How to get the URL of a xmlhttp request (AJAX)

On w3schools.com (url) there is an example of how to do an AJAX call with plain Javascript. w3schools.com (url)上,有一个如何使用纯Javascript进行AJAX调用的示例。 If you look at the example you will see the call is triggered by a button: 如果查看示例,您将看到呼叫是由按钮触发的:

<button type="button" onclick="loadXMLDoc()">Change Content</button>

This is the function: 这是功能:

function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}

What I would like to do is get the URL of the outgoing AJAX call which is ajax_info.txt (url): 我想做的是获取传出的AJAX调用的URL,即ajax_info.txt (URL):

xmlhttp.open("GET","ajax_info.txt",true);

Im trying to put that URL in to an alert, so I tried calling the headers of the response using getAllResponseHeaders() hoping that it will give me the Host like so: 我试图将URL置于警报中,所以我尝试使用getAllResponseHeaders()调用响应的标头,希望它将像这样给Host

if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    alert(xmlhttp.getAllResponseHeaders());

It does give me all the headers but not the Host. 它确实给了我所有标头,但没有给主机。 So my next move was trying to set the Host myself using setRequestHeader() but then I realized the Header needs a Value which I had to send myself, so this will not work. 因此,我的下一个步骤是尝试使用setRequestHeader()自己设置主机,但随后我意识到Header需要一个必须发送给自己的值,因此它将无法正常工作。 What else can I try to get/fetch the outgoing AJAX URL in the alert? 我还能尝试什么方式来获取/获取警报中的传出AJAX URL?

Please note the code is just an example and I know that changing headers(in this case) is prohibited because of Access-Control-Allow-Origin. 请注意,该代码仅是示例,我知道由于Access-Control-Allow-Origin,禁止更改标头(在这种情况下)。

I'm not sure how much access you have to the code but you can over-ride XMLHttpRequest.open and hook the url there. 我不确定您对代码有多少访问权限,但是您可以覆盖XMLHttpRequest.open并将URL钩在那里。

XMLHttpRequest.prototype.open = (function(open) {
  return function(method,url,async) {
      console.log('the outgoing url is ',url);
      open.apply(this,arguments);
    };
})(XMLHttpRequest.prototype.open);

Here is a FIDDLE . 这是一块FIDDLE

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

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