$ http.get(url)不起作用
问题描述:
我正在使用$ http从另一个文件中使用角度js获取细节。
<body>
<h2>AngularJS</h2>
<div ng-app = "" ng-controller = "sController">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat = "student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
<script>
function studentController($scope,$http) {
var url = "C:\\Users\\Test\\Desktop\\data.txt";
$http.get(url).success(function(response) {
alert('success');
$scope.students = response;
}).error(function (response) {
alert("error");
return status;
});
}
</script>
的data.txt文件包含JSON格式的学生的详细信息。
[{"Name" : "Smith","RollNo" : 11,"Percentage" : "80%"}]
控制不进去成功。我错过了什么吗?此外,我没有得到任何回应。请帮忙。
答
这是一个http请求,该文件应该托管在某个地方,并且始终将json作为json扩展文件更好。
有你的代码的几个问题,
(我)我没有看到一个模块名称
(ii)您已经定义了控制器sController
,并用它作为studentController
检查此样本
app.controller("MyController", ["$scope","$http",
function($scope, $http) {
$http.get('test.json').then(function (response){
$scope.students = response.data;
console.log(response.data);
});
}]);
这里工作sample
答
请function.Use sController
而不是studentController
校正控制器的名字和你正在$http
请求,所以它会发现它在某些URL或者http://localhost
或任何其他domain
主办的文件。
HTML:
<div ng-app = "MyApp" ng-controller = "sController">
脚本:
<script>
var app = angular.module("MyApp",[]);
app.controller("sController",function ($scope,$http) {
var url = "http://www.example.com/data.txt";
$http.get(url).success(function(response) {
alert('success');
$scope.students = response;
}).error(function (response) {
alert("error");
return status;
});
});
</script>
答
我已经修改了你的代码,在那里我已经直接从文本阅读的内容,使之易于理解,您可以添加“http”来从URL上下文中读取内容。
这个AngularJS代码有正确的模块和控制器注册到模块部分,我已经测试并附上下面的屏幕截图。
请让我知道,如果您有任何疑问。
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="[email protected]" src="https://code.angularjs.org/1.0.8/angular.js"
data-semver="1.0.8"></script>
<script>
var app = angular.module('MyApp', []);
app.controller('MainCtrl', function($scope) {
$scope.name = "World";
var text =
'[{"Name" : "Smith","RollNo" : 111,"Percentage" : "80%"}]';
var obj = JSON.parse
(text);
$scope.students = obj;
});
</script>
</head>
<body ng-
controller="MainCtrl">
<p>Hello {{name}}!</p>
<div ng-controller="MainCtrl">
<table>
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>
</body>
</html>
你注册你的控制器? ('angular.module(moduleName).controller ...' – AranS
创建一个角度模块并引用应用程序名称,同时向控制器注册App名称 –