在w3schools.com (url) 上有一个示例,说明如何使用纯 Javascript 进行 AJAX 调用。如果您查看示例,您将看到调用是由按钮触发的:
<button type="button" onclick="loadXMLDoc()">Change Content</button>
Run Code Online (Sandbox Code Playgroud)
这是函数:
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();
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是获取传出 AJAX 调用的 URL,即ajax_info.txt (url):
xmlhttp.open("GET","ajax_info.txt",true);
Run Code Online (Sandbox Code Playgroud)
我试图将该 URL 放入警报中,所以我尝试调用响应的标头,getAllResponseHeaders()希望它会给我Host这样的:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
alert(xmlhttp.getAllResponseHeaders());
Run Code Online (Sandbox Code Playgroud)
它确实给了我所有的标题,但没有给我主机。所以我的下一步是尝试自己设置主机,setRequestHeader()但后来我意识到标题需要一个我必须自己发送的值,所以这行不通。我还能尝试获取/获取警报中的传出 AJAX URL 吗? …