如何使用基本身份验证和jQuery和Ajax [英] How to use Basic Auth and Jquery and Ajax

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

问题描述

我想创建通过浏览器中的基本认证,但我真的不能到那里。

如果该脚本将不会在这里浏览器AUTH将接管,但我要告诉用户将进行身份验证的浏览器。

地址应该是这样的:

 的http://用户名:password@server.in.local/
 

我有一个表格:

 <表格名称=cookieformID =登陆的方法=邮报>
      <输入类型=文本名称=用户名ID =用户名级=文本/>
      <输入类型=密码NAME =密码ID =密码级=文本/>
      <输入类型=提交名称=分值=提交级=页/>
< /形式GT;
 

和一个脚本:

 变种的用户名= $(#输入用户名)VAL()。
。VAR密码= $(#输入密码)VAL();

功能make_base_auth(用户名,密码){
  VAR TOK =用户+:+通过;
  VAR哈希= Base64.en code(TOK);
  返回基本+散;
}
$就
  ({
    键入:GET,
    网址:index1.php
    数据类型:JSON,
    异步:假的,
    数据:{用户名:'+用户名+',密码:'+密码+}',
    成功:函数(){
    警报(感谢您的评论!);
    }
});
 

解决方案

使用jQuery的beforeSend回调添加一个HTTP标头的身份验证信息:的 http://api.jquery.com/jQuery.ajax/

  beforeSend:功能(XHR){
    xhr.setRequestHeader(授权,基本+ BTOA(用户名+:+密码));
},
 

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

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

The address should be something like:

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

I have a form:

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

And a script:

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

function make_base_auth(user, password) {
  var tok = user + ':' + pass;
  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!'); 
    }
});

解决方案

Use jQuery's beforeSend callback to add an HTTP header with the authentication information: http://api.jquery.com/jQuery.ajax/

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

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

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