2017-08-06 130 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) –