我想讓我的ajax調用工作來連接到使用ServiceStack的API。我遇到的問題是身份驗證。在C#我做的呼叫是這樣的:ServiceStack + Ajax身份驗證呼叫
string json = "";
JsonServiceClient client;
client = new JsonServiceClient("https://api.domain.com");
client.SetCredentials("test", "test");
client.AlwaysSendBasicAuthHeader = true;
try
{
List<AppleResponse> response = client.Get<List<AppleResponse>>("/v1/getdata?id=1");
json = response.ToJson();
}
catch (Exception ex)
{
json = ex.Message;
}
JArray v = JArray.Parse(json);
var total = v[0]["total"].ToString();
我得到的總的價值,例如總= 10 現在我想做的使用Ajax調用同樣的事情。這裏是未經驗證即可調用示例:
function Getdata(id) {
$.ajax({
url: '//api.domain.com/v1/getdata',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id_s: id }),
success: function (f) {
$.each(f.d, function (i, e) {
alert(e.total);
});
},
cache: false
});
}
有誰知道我怎麼能加入身份驗證,但不顯示在JavaScript標記中的用戶名/密碼?非常感謝。
可以保存在頭的身份驗證令牌,並將其發送的每當你做阿賈克斯呼叫。 – reptildarat
謝謝reptildarat,你知道確切的語法嗎?像這樣:$ .ajax({url:'//api.domain.com/v1/getdata', type:「POST」, contentType:「application/json; charset = utf-8」,auth :<%= client %>,數據:... – carol1287