2013-08-06 19 views
0

我們試圖從變量(數據)中獲取json值,並將其作爲輸入以json的形式輸入到D3中。但它在螢火蟲中發出錯誤,說「data.links未定義」。 如果我們使用d3.json()函數從sample.json文件中獲取json值,但是沒有使用該變量,則此圖表會很好。json的D3值變量的值拋出error.While靜態json文件工作正常

下面

是樣品JSON,

{ 
"nodes": [ 
    { 
     "group": "pepsi", 
     "name": "solly", 
     "size": 20 
    }, 
    { 
     "group": "coke", 
     "name": "ROBdey", 
     "size": 7 
    }, 
    { 
     "group": "limca", 
     "name": "Mike", 
     "size": 5 
    }, 
    { 
     "group": "coke", 
     "name": "OFFA", 
     "size": 1 
    }, 
    { 
     "group": "limca", 
     "name": "deuje", 
     "size": 1 
    }, 
    { 
     "group": "pepsi", 
     "name": "EITAKdell", 
     "size": 1 
    }, 
    { 
     "group": "coke", 
     "name": "COOK", 
     "size": 1 
    }, 
    { 
     "group": "pepsi", 
     "name": "CRISLY", 
     "size": 1 
    } 
], 
"links": [ 
    { 
     "source": 3, 
     "target": 3, 
     "value": 1 
    }, 
    { 
     "source": 4, 
     "target": 4, 
     "value": 1 
    }, 
    { 
     "source": 7, 
     "target": 57, 
     "value": 1 
    }, 
    { 
     "source": 10, 
     "target": 10, 
     "value": 1 
    }, 
    { 
     "source": 12, 
     "target": 332, 
     "value": 1 
    }, 
    { 
     "source": 14, 
     "target": 325, 
     "value": 1 
    }, 
    { 
     "source": 17, 
     "target": 548, 
     "value": 1 
    }, 
    { 
     "source": 19, 
     "target": 157, 
     "value": 1 
    } 
] 
} 

和D3代碼是在這裏

我們試圖retriev從MongoDB的REST API調用與我們使用becasue JSON格式jquery.This數據從mongoDB返回的結果並不精確。

+0

你能交叉檢查你是否從調用中獲得正確的json數據。如果是的話,它的格式是否正確? – Akki619

回答

1

根據與引擎收錄粘貼代碼,這裏的功能如何假人的樣子:

function dummy() { 
    var form_data = { 
     user: "example.com/foo", 
     is_ajax: 1 
    }; 
    $.ajax({ 
     type: "GET", 
     url: form_data.user, 
     contentType: "application/jsonp", 
     dataType: "jsonp", 
     jsonp: "jsonp", 
     cache: false, 
     success: function (data) { 
      var t = data.rows[0]; 
      delete t["_id"]; 
      markers = JSON.stringify(t); 
     } 

    }); 
    return markers; 
} 

它沒有工作,因爲它是不可能從這樣的異步調用返回的值。當您嘗試返回它時,markers未定義。

編輯:

由於moonwave99指出的那樣,你應該處理您的數據成功回調:

function dummy() { 
    var form_data = { 
     user: "example.com/foo", 
     is_ajax: 1 
    }; 
    $.ajax({ 
     type: "GET", 
     url: form_data.user, 
     contentType: "application/json", 
     dataType: "jsonp", 
     jsonp: "jsonp", 
     cache: false, 
     success: function (data) { 
      var t = data.rows[0]; 
      delete t["_id"]; 
      markers = JSON.stringify(t); 

      processMarkers(markers); 
     } 

    }); 
} 

你應該將大部分的全球範圍的代碼到processMarkers功能。此外,dummy不再是這種功能的好名字。

+2

這也行不通 - 你必須在回調中做你的生意。 – moonwave99

+0

是的,你是對的。我會相應地編輯。 – lifus