我想仅在用户写入用户名和密码时才使用授权标准创建ajax调用。当这些变量为空时,我需要创建一个没有授权标头的ajax调用。我怎样才能做到这一点?我可以用一个ajax制作它还是我需要在一种情况下创建两个ajax?
var username = "user123";
var password = "pass123";
//var username = "";
//var password = "";
$.ajax({
type: "GET",
url: url_survey,
dataType: "json",
headers: {
'Authorization': "Basic " + btoa(username + ":" + password)
},
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
});
答案 0 :(得分:2)
试试这个:
var username = "user123";
var password = "pass123";
//var username = "";
//var password = "";
var headers = {}; //list of headers
if(username && password) //user and pass exists
headers['Authorization'] = "Basic " + btoa(username + ":" + password);
$.ajax({
type: "GET",
url: url_survey,
dataType: "json",
headers: headers, //use our headers
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
});
答案 1 :(得分:1)
传递给$.ajax
的参数只是一个对象。只需创建它,根据需要添加属性,然后将其发送到`$ .ajax。
var ajaxData = {
type: "GET",
url: url_survey,
dataType: "json",
success:
function (data) {
alert("SUCCESS");
},
error:
function (data) {
alert("ERROR");
}
};
if(username && password){
ajaxData.headers = {
'Authorization': "Basic " + btoa(username + ":" + password)
};
}
$.ajax(ajaxData);