jQuery AJAX标头授权 [英] jQuery AJAX Header Authorisation

查看:60
本文介绍了jQuery AJAX标头授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于

I'm trying to authorise an AJAX query based on this tutorial. It sets the request headers before send with the appropriate authorisation information by using the Crypto library. The problem I'm having is that headers don't seem to be set on request. Here's my code:

beforeSend : function(xhr) {
  var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
  var base64 = Crypto.util.bytesToBase64(bytes);
  xhr.setRequestHeader("Authorization", "Basic " + base64);
},

推荐答案

问题不是将dataType设置为JSONP.由于未完成此操作,浏览器将呼叫解释为标准AJAX请求,这意味着该呼叫已在same-origin-policy下被阻止.

The issue was not setting the dataType to JSONP. As this was not done the browser interpreted the call as a standard AJAX request which meant it was being blocked under same-origin-policy.

工作代码以供参考(有关建议Crpyto的信息,请访问@pdeschen):

Working code for reference (credit goes to @pdeschen for suggesting Crpyto):

<script type='text/javascript'>
// define vars
var username = '';
var password = '';
var url = '';

// ajax call
$.ajax({
    url: url,
    dataType : 'jsonp',
    beforeSend : function(xhr) {
      // generate base 64 string from username + password
      var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
      var base64 = Crypto.util.bytesToBase64(bytes);
      // set header
      xhr.setRequestHeader("Authorization", "Basic " + base64);
    },
    error : function() {
      // error handler
    },
    success: function(data) {
        // success handler
    }
});
</script> 

这篇关于jQuery AJAX标头授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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