在AngilarJS中使用get请求时出错

时间:2018-08-28 07:40:11

标签: angularjs

我有一些JSON数据存储在文件weeklyData.json(位于文件夹 json 中)中,我想使用GET请求在控制台中显示该文件,但得到结果< strong>未定义。

我的app.js文件包含两种用于GET请求的方法,但结果保持不变:未定义

HTML文件:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Crazy Data Component</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>

<body ng-app="myApp" ng-controller="myCtrl">
    <h1>{{msg}}</h1>
    <script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
    <script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="js/app.js"></script>
    <!--    <script src=""></script>-->
</body>

</html>

app.js

var myApp = angular.module("myApp", []);

myApp.controller("myCtrl", function ($scope, $http) {
    $scope.msg = "Something";
    $http({
        method: 'GET',
        url: 'json/weeklyData.json',
        headers: {
            'Content-type': 'application/json'
        }
    }).then(function (response) {
        console.log(response.data)
    }, function (error) {
        console.log(error.data)
    })
})

//    $http.get('json/weeklyData.json').success(function (data) {
//        $scope.dub = data;
//        console.log('$scope.dub', $scope.dub);
//    })
//})

有人可以提出建议吗?

1 个答案:

答案 0 :(得分:0)

您的代码正在运行。.检查以下代码段

您的示例json无法访问。检查您的网址。

var myApp = angular.module("myApp", []);

myApp.controller("myCtrl", function ($scope, $http) {
    $scope.msg = "Something";
    $http({
        method: 'GET',
        url: 'https://www.w3schools.com/angular/customers.php',
        headers: {
            'Content-type': 'application/json'
        }
    }).then(function (response) {
        console.log(response.data)
    }, function (error) {
        console.log(error.data)
    })
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Crazy Data Component</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="plugins/bootstrap_Plugin/css/bootstrap.min.css">
</head>

<body ng-app="myApp" ng-controller="myCtrl">
    <h1>{{msg}}</h1>
    <script src="plugins/bootstrap_Plugin/jquery.min.js"></script>
    <script src="plugins/bootstrap_Plugin/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script src="js/app.js"></script>
    <!--    <script src=""></script>-->
</body>

</html>