开发者

How to send GET request with login (user:pass) from a button?

开发者 https://www.devze.com 2023-03-28 00:20 出处:网络
I want a button on a webpage that, when pressed, does th开发者_如何学编程e equivalent of entering this url in the browser and hitting enter.

I want a button on a webpage that, when pressed, does th开发者_如何学编程e equivalent of entering this url in the browser and hitting enter.

http://user:pass@www.example.com/example/button_24

The code below gives me the button but it seems that it doesn't want to pass the credentials, firebug says this:

Access to restricted URI denied" code: "1012

if i remove the credentials it says 401 Unauthorized

Thanks in advance!

<html>
<head>
<script type="text/javascript">
function simpleAjax()
{
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("Divku").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","http://user:pass@www.example.com/example/button_24",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="simpleAjax()">Request data</button>
<div id="Divku"></div>

</body>
</html>

new code

<head> <meta http-equiv="refresh" content="30" >  </head>
<img alt="screenshot" src="http://a:a@www.example.com/example/screenshot.jpg">
<head>
<script type="text/javascript">
function simpleAjax()
{
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("Divku").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.setRequestHeader('Authorization','Basic YTph');
xmlhttp.open("GET","http://www.example.com/example/button_24",true);
xmlhttp.send();
}
</script>
</head>
<body>
<br>
<button type="button" onclick="simpleAjax()">Volume Up</button>
<div id="Divku"></div>

</body>


I think you need to setRequestHeader on the AJAX object and supply the Authentication header instead of passing it in the URL. Remember the server is looking for the header

Authorization: Basic abc123==

(or some facsimile).

Maybe check out this link on supplying credentials with AJAX requests?

ALSO, MDN on setRequestHeader method.

0

精彩评论

暂无评论...
验证码 换一张
取 消