显然我是新手。我正在尝试通过ajax加载一个json文件,然后循环该数组以使用cytoscape.js包填充图形(另一个问题改天再问)。在开始循环以创建新节点和边之前,我尝试测试我的循环以验证输出。但是,没有什么是不起作用的。
<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}我在这里做错了什么?谢谢
发布于 2015-06-11 02:40:14
这是因为$.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
发布于 2015-06-11 02:39:33
主要的问题是$.ajax不会返回json。它将把它注入一个成功的回调函数中。因此,您需要做的是将使用$.ajax中的"value“的预期代码移到success函数的内部。
$.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
}
}); 发布于 2015-06-11 02:43:08
Ajax查询是异步的,您必须等待它完成:
var query = $.ajax({url: url', // tokyo-railways.json type: 'GET', dataType: 'json' }) .done(function( graphP ) { //Your code here console.log(graphP); });
https://stackoverflow.com/questions/30764605
复制相似问题