2017-08-06 53 views
0

我想从我的JSON文件数据的使用,以获得从JSON文件中获取数据AngularJs 1.6不使用angularjs 1.6

myApp.controller("homeCtrl", function($scope, $http) { 
     $scope.Data = []; 
     var getJsonData = function() { 
      $http.get('contactlist.json').then(function(response) { 
       $scope.Data = response.data; 
       console.log(response.data); 
      }); 
     } 
     getJsonData(); 
    }); 

但它不会响应我正在调试上则行,但我的网页没有开通停止调试响应。所以它不会在那么(函数(效应初探){

我的JSON文件:

var contactList = [ 
{ 
"firstName": "Joe", 
"lastName": "Perry", 
"contactNumber": "444-888-1223", 
"contactEmail": "[email protected]" 
}, 
{ 
"firstName": "Kate", 
"lastName": "Will", 
"contactNumber": "244-838-1213", 
"contactEmail": "[email protected]" 
} 
]; 
+0

console.log(响应)的日志是什么? –

+0

它没有被触发 –

+0

在控制台中的任何错误? –

回答

0

从你删除var contactList =JSON文件并将JSON内容仅

,如:

[ 
    { 
     "firstName": "Joe", 
     "lastName": "Perry", 
     "contactNumber": "444-888-1223", 
     "contactEmail": "[email protected]" 
    }, 
    { 
     "firstName": "Kate", 
     "lastName": "Will", 
     "contactNumber": "244-838-1213", 
     "contactEmail": "[email protected]" 
    } 
] 

var contactList = <something>表示它的JavaScript代码需要执行,但您正在读取该文件并将其解析为json数据,而不是作为js文件,所以使它像一个JSON文件,所以内容只是JSON字符串,而不是一些JavaScript代码。

+0

我已经试过这个,但失败 –

+0

在这种情况下,确切的失败消息/日志是什么? –

+0

错误:[$ http:baddata]数据必须是有效的JSON对象。收到:“[{”id“:1}”“。解析错误:“{}” http://errors.angularjs.org/1.6.4/$http/baddata?p0=%5B%7B%22id%22%3A1%7D&p1=%7B%7D at angular。 JS:66 在defaultHttpResponseTransform(angular.js:11177) 在angular.js:11270 在的forEach(angular.js:403) 在transformData(angular.js:11269) 在transformResponse(angular.js:12090) at processQueue(angular.js:16832) at angular.js:16876 at Scope。$ digest(angular.js:17971) at Scope。$ apply(angular。js:18269)“可能未处理的拒绝:{}” –

0

更改您的JSON文件(你的JSON是无效的):

[{"firstName":"Joe","lastName":"Perry","contactNumber":"444-888-1223","contactEmail":"[email protected]"},{"firstName":"Kate","lastName":"Will","contactNumber":"244-838-1213","contactEmail":"[email protected]"}] 
1

得到它解决。问题是因为json文件数据末尾有分号。 尝试粘贴Plunker编辑器时出现此错误 我的错误。

+1

在我的答案中看到我也删除了这个,并为您提供了一个可行的JSON ... :) –

+0

是的,您是对的。这有帮助。谢谢Kaushik –

+0

如果你觉得真的有帮助,然后标记为接受为了帮助其他人(包括我:P) –