使用 jQuery 和 Ajax 进行基本身份验证 [英] Use basic authentication with jQuery and Ajax

查看:38
本文介绍了使用 jQuery 和 Ajax 进行基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过浏览器创建基本身份验证,但我无法真正做到.

I am trying to create a basic authentication through the browser, but I can't really get there.

如果此脚本不在这里,浏览器身份验证将接管,但我想告诉浏览器用户即将进行身份验证.

If this script won't be here the browser authentication will take over, but I want to tell the browser that the user is about to make the authentication.

地址应该是这样的:

http://username:password@server.in.local/

我有一个表格:

<form name="cookieform" id="login" method="post">
      <input type="text" name="username" id="username" class="text"/>
      <input type="password" name="password" id="password" class="text"/>
      <input type="submit" name="sub" value="Submit" class="page"/>
</form>

还有一个脚本:

var username = $("input#username").val();
var password = $("input#password").val();

function make_base_auth(user, password) {
  var tok = user + ':' + password;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}
$.ajax
  ({
    type: "GET",
    url: "index1.php",
    dataType: 'json',
    async: false,
    data: '{"username": "' + username + '", "password" : "' + password + '"}',
    success: function (){
    alert('Thanks for your comment!');
    }
});

推荐答案

使用jQuery的beforeSend 回调添加带有身份验证信息的 HTTP 标头:

Use jQuery's beforeSend callback to add an HTTP header with the authentication information:

beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

这篇关于使用 jQuery 和 Ajax 进行基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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