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

2019-01-29 12:45发布

On w3schools.com(url) there is an example of how to do an AJAX call with plain Javascript. 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):

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:

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. What else can I try to get/fetch the outgoing AJAX URL in the alert?

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.

1条回答
萌系小妹纸
2楼-- · 2019-01-29 13:14

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.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.

查看更多
登录 后发表回答