<html>
<head>
<title>Springy.js image node demo</title>
</head>
<body>
<script src="jquery-1.11.3.js"></script>
<script src="springy.js"></script>
<script src="springyui.js"></script>
<script src="bluebird.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
// get exported json from cytoscape desktop via ajax
var graphP = $.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json'
});
console.log(graphP);
var node = graphP.nodes;
//var employee2 = elements.edges;
for ( var i in node) {
var id = nodes[i].id;
var station_name = nodes[i].station_name;
console.log(id);
console.log(station_name);
}
</script>
</body></html>
这应该产生节点id和站名的输出,但它不是。控制台。(日志)生成:对象{readyState:1} 我在这做错了什么? 感谢
答案 0 :(得分:2)
这是因为$.ajax
是异步。
尝试:
// get exported json from cytoscape desktop via ajax
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json'
}).done(function (graphP) {
console.log(graphP);
var node = graphP.nodes;
//var employee2 = elements.edges;
for ( var i in node) {
var id = nodes[i].id;
var station_name = nodes[i].station_name;
console.log(id);
console.log(station_name);
}
});
请参阅demo
答案 1 :(得分:0)
<强> jsFiddle Demo
强>
主要问题是$.ajax
不会返回json。它将把它注入成功的回调函数。因此,您需要做的是将您期望的代码移到下面,该代码使用$.ajax
中的“值”在成功函数内部。
$.ajax({
url: 'https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json', // tokyo-railways.json
type: 'GET',
dataType: 'json',
success: function(graphP){
console.log(graphP);
//the structure of the json is slightly different than your mappings
//for example
var firstNodeId = graphP.elements.nodes[0].data.id;//is the first id
}
});
答案 2 :(得分:0)
Ajax查询是异步的,您必须等待它完成:
var query = $.ajax({url: url', // tokyo-railways.json
type: 'GET',
dataType: 'json'
})
.done(function( graphP ) {
//Your code here
console.log(graphP);
});
答案 3 :(得分:0)
尝试使用:
$.getJSON( "https://rawgit.com/theresajbecker/CompBio/master/TokyosmallTest/Tokyosmall2.json", function( data ) {
for (var i = 0; i < data.elements.nodes.length; i++) {
var node = data.elements.nodes[i];
console.log(node.data.id);
}
});