Извинения, ако е написано неловко, но трябва да направяобаждане в API с помощта на jQuery. Вече съм осъществил разговора, използвайки angularJS, но за този случай не мога да го използвам. Опитах се да го преведа на jQuery, но не получавам същите резултати. Има ли нещо, което правя неправилно или ми липсва информация? Аз съм сравнително нов за jQuery, така че се чувствам сякаш ми липсва нещо решаващо или неразбрано нещо.
Работен код с ъгълJS:
var req = {
method: "POST",
url: "https://fakeurl.com/rest/v1/portal/user/" + $scope.email.value,
headers:{
"Content-Type": "application/json",
"Header_1": "Yes",
"x-access-token": "glsFromWebsite" //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === "601") {
console.error("Token is invalid or has expired");
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error("Error calling rest endpoint",err);
reject();
});
} catch (ex) {
console.error("Exception calling rest endpoint",ex);
reject(ex);
}
});
};
Моят неуспешен jQuery код:
var processCreate = function (email) {
$.ajax({
url: "https://fakeurl.com/rest/v1/portal/user/" + email.value,
type: "POST",
headers: {
"Content-Type": "application/json",
"Header_1": "Yes",
"x-access-token": "glsFromWebsite" //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === "NOT FOUND") {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Отговори:
1 за отговор № 1Опитайте да извършите ajax разговор по този начин
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = "Bearer " + "glsFromWebsite";
$.ajax({
url: "https://fakeurl.com/rest/v1/portal/user/" + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === "NOT FOUND") {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}