$ http请求的代码有什么问题?

时间:2013-09-20 05:23:45

标签: javascript http angularjs

我的index.html是:

<!DOCTYPE html>
<html lang="en" ng-app="myApp">

<head>
  <meta charset="utf-8">

  <title>HTTP Request</title>

  <script src="angularjs"></script>
  <script src="appjs"></script>

</head>
<body>

    <div ng-controller="myCtrl">

        Test here : <input ng-model="testString">
        <p>Test String is : {{testString}}</p>
        <button ng-click="search()">Send HTTP Request</button>
        <p>Response:</p>
        {{data}}
    </div>

</body>
</html>

我的app.js是:

angular.module('myApp', [])
    .controller('myCtrl', ['$scope', '$http', function($scope, $http) {
        $scope.testString = "Hello....";

        $scope.search = function() {
//          alert("inside search");
            $http.get('www.google.com', {},
                function(response) {
                    $scope.data = response;
                    alert("success");
                },
                function(failure) {
                    alert("failure");
            });
        };
    }]);

根据警报(“内部搜索”)进入search()函数。但我既没有得到回应也没有失败。我该怎么办?

2 个答案:

答案 0 :(得分:2)

您需要使用.success.errorAngular http docs检索结果,例如

$http.get('http://www.google.com').
    success(function(response) {
                $scope.data = response;
                alert("success");
            }).
    error(function(failure) {alert("failure")});

答案 1 :(得分:1)

 $http.get('www.google.com', {},
            function(response) {
                $scope.data = response;
                alert("success");
            },
            function(failure) {
                alert("failure");
});

替换为:

$http.jsonp('http://www.google.com', {})
         .success(function(response, status) {
             $scope.data = response;
                alert("success");
        })
        . error(function(data, status) {
             alert("failure");
     });

DEMO