你如何使用jQuery调用需要基本身份验证的JSON Web服务?

ace*_*ole 12 javascript jquery json

我在javascript上有点新手,但我试图调用一个JSON Web服务,需要使用jQuery进行基本身份验证(或任何可以正常工作的东西).

我无法在谷歌上找到任何真正的答案.我正在尝试做什么?

mel*_*okb 10

您需要设置适当的请求标头以传递凭据.例如,请看这里.

$.getJSON({
    'url': 'http://host.com/action/',
    'otherSettings': 'othervalues',
    'beforeSend': function(xhr) {
        //May need to use "Authorization" instead
        xhr.setRequestHeader("Authentication",
            "Basic " + encodeBase64(username + ":" + password)
    },
    success: function(result) {
        alert('done');
    }
});
Run Code Online (Sandbox Code Playgroud)

仅供参考我搜索谷歌jquery post with basic auth,这是第一个链接.

  • 正确,这就是基本身份验证的工作原理.我也不推荐它,但它是OP所要求的. (4认同)
  • 您可以使用https而不是http,那么它将不会是明文 (3认同)

Phi*_*ret 7

以下是使用jQuery进行复制和粘贴需求的方法:

$.ajax({
    url: "/somewhere",
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic " + window.btoa(username + ":" + password));
    },
    success: function(result) {
        console.log(arguments);
    }
});
Run Code Online (Sandbox Code Playgroud)