如何在Ajax调用中设置标头?

时间:2017-04-11 12:43:53

标签: javascript ajax

我正在开发使用Angularjs和Web api作为后端的多语言网站。每当我进行API调用时,我都会尝试在标头中发送RequestedPlatformRequestedLanguage

以下是我的Ajax请求调用。

$http.post(url,RegistrationData).then(function (response) {
                   var pageList = response.data.ID;
                   toastr.success('', 'Registered Succesfully');
                   $state.go('Registration.OTPVerification', { pageList });
               }, function (error) {
                   toastr.error('', 'Error Occured');
               });

更新代码

var RegistrationData = {
                   FirstName: $scope.user.Fname,
                   LastName: $scope.user.Lname,
                   Password: $scope.user.password,
                   Gender: "Male",
                   DateOfBirth: "2017-04-04",
                   Nationality: $scope.user.selectedGlobe,
                   Mobile_CountryCod: "91",
                   MobileNumber: $scope.user.mobilenumber,
                   EmailId: $scope.user.email,
                   Home_Location: $scope.user.homeLocation,
                   Home_City: $scope.user.homeCity,
                   Home_Neighbourhood: $scope.user.homeNeighbourhood,
                   Home_HouseNumber: $scope.user.housenumber,
                   Home_MainStreet: $scope.user.homemainstreet,
                   Home_SubStreet: $scope.user.homesubstreet,
                   Work_Location: $scope.user.worklocation,
                   Work_City: $scope.user.workcity,
                   Work_Neighbourhood: $scope.user.workNeighbourhood,
                   Work_HouseNumber: $scope.user.workhousenumber,
                   Work_MainStreet: $scope.user.workmainstreet,
                   Work_SubStreet: $scope.user.worksubstreet
               };
               var req = {
                   method: 'POST',
                   url: url,
                   data: { RegistrationData: RegistrationData },
                   headers: {
                       RequestedPlatform: "Web",
                       RequestedLanguage: "English"
                   }
               }
               $http(req).then(function (response) {
                   var pageList = response.data.ID;
                   toastr.success('', 'Registered Succesfully');
                   $state.go('Registration.OTPVerification', { pageList });
               }, function () {
                   toastr.error('', 'Error Occured');
               });

我可以帮助在Ajax中设置标头。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

有几种方法,我已经发布了一段时间我一直使用它的方法。我希望你正在寻找下面的

$http.post('test', data, {
        withCredentials : false,
        transformRequest : angular.identity,
        headers : {
            'Content-Type' : undefined
        }
})

答案 1 :(得分:1)

您可以发送headers属性$ http

的标头
var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined
 },
 data: { test: 'test' }
}

$http(req).then(function(){...}, function(){...});

如果您希望通过访问$httpProvider.defaults.headers配置对象完全配置所有请求的标头,

Reference