我正在尝试加载要求用户名和密码的XML文件。

我正在使用的代码如下,我试图在URL中发送用户名和密码:

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false);


我页面的完整代码如下所示:

<html>
<body>

<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>

<script type="text/javascript">

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("test1").value=xmlhttp.responseText;
     } else
     {
     alert('Panel not communicating.Reason: '+xmlhttp.status);
     }
   }

xmlhttp.open("POST","http://admin:admin@192.168.0.5/myfile.xml",false);
xmlhttp.send();

</script>
</body>
</html>


有人知道我在做什么错吗?

最佳答案

首先,添加此函数以创建授权标头内容:

function make_base_auth(user, password)
{
  var tok = user + ':' + pass;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}


然后,调用该函数并将返回值存储在单独的变量中:

var auth = make_basic_auth('admin', 'admin');


最后,将auth的值传递给XMLHttpRequest对象:

xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();




归因:http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html

10-06 15:34
查看更多