我已經盡了一切努力將我的JSON數據(JSON對象?)與$ http.get(「https://server url to my json data」).javascript(function(response){} )分配給javascript中的局部變量,但它doesnt't的工作。我與這一切JSON字符串和對象的真糊塗。這裏是我的代碼。我的JSON數據如何從http.get(//從服務器的json)到Javascript變量分配JSON數據?
形式,我從服務器
{
"status":"success",
"data":{
"user":{
"username":"user1",
"fullName":"name "
},
"vehicles":[ ],
"chargeBoxes":
[
{
"id":1,
"name":"Station 1",
"availability":"offline",
},
{
"id":2,
"name":"Station 2",
"availability":"online",
},
{
"id":3,
"name":"Station 3",
"availability":"online",
}
]
}
所以得到的,我的問題是我如何使用這個數據存儲它在一個js數組。我需要它爲我的javascript高圖形控制器。我試過這..
個controller.js
myApp = angular.module('ServiceDashboard');
myApp.controller('DataController' function($scope, $http, $interval) {
$http.get("https://server-url.com/../login?username=..&password=..").success(function(response) {
$scope.jsonData = response.data;
});
var categorieData = [];
var json = JSON.parse(jsonData);
for (var i = 0; i <= jsonData.chargeBoxes.length - 1; i++)
{
categorieData[i] = jsonData.chargeBoxes[i].name;
}
//當我做這種方式(測試用例)(JSON變量只有一條線路,並與 '' 這工作真精
// Here I have a json string (one line with ' ')
var jsonData= '{"status": "success", "data": {"chargeboxes":[{..},{..},{..}]}';
// and then I parse this json string to an json object and iterate over it and store the chargeBoxes.name values into the categorieDate array.
但當我用我的json數據的真實形式(帶{}的多行)嘗試它時,它不起作用。
var jsonData = {
"status":"success",
"data":{
"user":{
"username":"user1",
"fullName":"name "
},
"vehicles":[ ],
"chargeBoxes":
[
{
"id":1,
"name":"Station 1",
"availability":"offline",
},
{
"id":2,
"name":"Station 2",
"availability":"online",
},
{
"id":3,
"name":"Station 3",
"availability":"online",
}
]
};
我真的不知道該做什麼了。首先,我想用一個像上面這樣的局部變量來嘗試它(var jsonData = {..};因爲使用oneline string''),然後我想直接從服務器使用這個json數據( $ scope.jsondata ...)。
謝謝!
你爲什麼'VAR JSON = JSON.parse(jsonData);'然後用'json'的'jsonData'instead?試試'for(var i = 0; i <= json.chargeBoxes.length - 1; i ++)...' – ojovirtual
你的問題沒有多大意義。您的controller.js代碼將不起作用,因爲Ajax是異步的。 「JSON數據的真實形式」根本不是JSON。 – Quentin
可能的重複[如何從異步調用返回響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Hacketo