给出以下index.html
<!DOCTYPE html>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
var nodes = [];
$.get("mappings/Actor.hbm.xml", function(d){
nodes.push({"id":nodes.length,
"label":$(d).find("class").attr("table"),
"x":0,
"y":0
});
});
console.log(nodes)
</script>
以下xml的使用
<hibernate-mapping>
<class name="nl.sander.mieras.localhost.sakila.Actor" table="actor" catalog="sakila">
当我将console.log(节点)放在方法体外时,控制台显示一个空数组[]。似乎将数据推送到var nodes数组中并不是在方法体的范围之外持久化。
如何将推送的数据保存/存储/保存/保持(不知道技术js术语)到var nodes数组中,以便能够在console.log(节点)中看到对象而不是空数组?
答案 0 :(得分:3)
看起来你在AJAX请求返回之前打印nodes
。请记住,JavaScript是异步的,因此不会立即调用您的回调。尝试设置超时并然后打印nodes
:
setTimeout(function () { console.log(nodes) }, 2000);
无论您需要对AJAX调用的响应做什么,都应该在回调中处理您遇到的确切问题;没有其他方法可以保证数据尚可用。