简体   繁体   English

在Ajax JSON脚本中添加基本的HTTP授权

[英]Adding basic http authorization in a ajax json script

Not really sure how to add authentication in an ajax call for JSON information. 不太确定如何在ajax调用中为JSON信息添加身份验证。 I am trying to follow the examples given http://domainapi.com/documentation/how-to-use-domainapi/servuces-provided/domain-availability-api.html to check the availability of a domain name, however it keeps doing a http form pop up asking for username and password. 我正在尝试按照http://domainapi.com/documentation/how-to-use-domainapi/servuces-provided/domain-availability-api.html给出的示例来检查域名的可用性,但是它一直在做弹出一个http表单,要求输入用户名和密码。

I thought I had everything right in my code: 我以为代码中的所有内容都正确无误:

function domainAvailabilityCheck(domain) {
    $.ajax({
        type: 'GET',
        url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
        beforeSend: setHeader,
        success: function(spitback) {
            console.log(spitback.content.domainList.status);
        },
        dataType:'jsonp'
    });
}

var setHeader = function(xhr) {
    xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}

Not sure what it is that I am doing wrong. 不知道我做错了什么。

Your beforeSend isn't allowing Jquery to pass in the xhr object for the header modifications. 您的beforeSend不允许Jquery传递xhr对象以进行标头修改。 The line should be 该行应该是

beforeSend: function(xhr) { xhr.setRequest(......); } // all-in-one, no extra function needed

or 要么

beforeSend: function(xhr) { setHeader(xhr); } // call your separate function

you may also: 您还可以:

var setHeader = function (xhr) {
    xhr.setRequestHeader('Authorization', 'Basic YWtpcmF0ZXN0OmR0d3N0ZXN0');
}

function domainAvailabilityCheck(domain) {
    $.ajax({
        type: 'GET',
        url: 'http://api.domainapi.com/v1/availability/'+domain+'.com',
        beforeSend: setHeader,
        success: function(spitback) {
            console.log(spitback.content.domainList.status);
        },
        dataType:'jsonp'
    });
}

actually it doesn't matter where to put the variable setHeader which holds the anonymous function, but this way up it's more readable (for me and my soft-compiler ... ;) 实际上,放置匿名函数的变量setHeader放在哪里都无所谓,但是这样一来,它更具可读性(对我和我的软编译器...而言)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM