Monday, July 10, 2017

AngularJS $http service returns html instead of JSON string

Good day!
I've been trying to consume an ASP.NET Web Method using AngularJS $http service and all I get from the response is the html page source instead of string data. After investigating and doing some searching, the workaround is to set the responseType to json and pass an empty data to the Web Method given that the Web Method has no parameter.
var myapp = angular.module('myApp', []);
myapp.controller('ctrl', function ($scope, $http) {
 $http({
  url: "63MakeAjaxCallAndReturnJSONWebService.aspx/HelloWorld",
  dataType: 'json',
  method: "POST",
  responseType: 'json',
  data: {},
  headers: { "Content-Type": "application/json;" }
 }).then(function (response) {
  $scope.value = response.data.d;
 });
});
And also declare the Web Method as static.
[WebMethod()]
public static string HelloWorld()
{
 return "Hello World!";
}

0 comments:

Post a Comment