如何获取 xmlhttp 请求的 URL (AJAX) [英] How to get the URL of a xmlhttp request (AJAX)

查看:34
本文介绍了如何获取 xmlhttp 请求的 URL (AJAX)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

w3schools.com(url) 上有一个例子如何使用纯 Javascript 进行 AJAX 调用.如果您查看示例,您将看到调用是由按钮触发的:

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>

这是函数:

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

我想要做的是获取传出 AJAX 调用的 URL,即 ajax_info.txt(网址):

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

我试图将该 URL 放入警报中,因此我尝试使用 getAllResponseHeaders() 调用响应的标头,希望它能给我 Host 像所以:

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

它确实给了我所有的标题,但没有给我主机.所以我的下一步是尝试使用 setRequestHeader() 自己设置主机,但后来我意识到标题需要一个我必须自己发送的值,所以这行不通.我还可以尝试获取/获取警报中的传出 AJAX URL 吗?

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?

请注意,代码只是一个示例,我知道由于 Access-Control-Allow-Origin 禁止更改标题(在这种情况下).

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.

推荐答案

我不确定您对代码有多少访问权限,但您可以覆盖 XMLHttpRequest.open 并挂钩 url

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

这是一个FIDDLE.

这篇关于如何获取 xmlhttp 请求的 URL (AJAX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆