Saturday, July 25, 2015

$http vs JSONP for cross-site request

In the previous posts we saw on how to make Ajax requests using $http and JSONP, we also saw that $http does not support cross-site server requests, and JSONP supports it. In this post we shall see an example of making cross-site service requests using $http and JSONP and observer the responses in both the cases.

The following example makes the same Ajax calls using JSONP and $http, let us observe the response from both the requests.

<html ng-app>
<head>
    <meta charset="utf-8" />
    <title>AngularJS - Basic</title>
    <script src="angular.min.js"></script>
        <script>
                function httpAjaxController($scope,$http){
                       $scope.Title = "Package List";

                             // JSONP cross-site Request
                             $http.jsonp("http://localhost/BasicWebAPI/api/ContactType?callback=JSON_CALLBACK")
                             .then(function (results) {
                                                alert(results.data);
                             }, function (results) {
                                      //error
                                      alert("Error: " + results.data + "; "
                                                                                        + results.status);
                             })
                             //
                             // $http cross-site Request
                             $http.get("http://localhost/BasicWebAPI/api/ContactType")
                             .then(function (results) {
                                                alert(results.data);
                             }, function (results) {
                                      //error
                                      alert("Error: " + results.data + "; "
                                                                                        + results.status);
                             })
                }
    </script>
</head>
<body>
          <div ng-controller="httpAjaxController">
                    <b>{{Title}}</b><br/>
                    <ul>
                       <li ng-repeat="package in packageList">
                         {{ package.PackageId }} - {{ package.Name }}<br/>
                       </li>
                   </ul>
          </div>
</body>
</html>

Response

AngularJS $http vs JSONP


Search Flipkart Products:
Flipkart.com

No comments: