我制作了一个简单的 JS,它从我的 servlet 中检索数据。我收到的数据是两个随机数。我想每 3 秒打印一次这个值。
<html>
<head>
<button onclick="getP()">Try it</button>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var arr = new Array();
var url = "http://10.10.1.19:8080/examples/MyHelloWorld";
function getPos() {
var jqxhr = $.getJSON(url+"?getpos&callback=?",
function(data) {
//alert("success x " + data.x + ", y: " + data.y);
arr[0] = data.x;
arr[1] = data.y;
})
.success(function(data) {
//alert("second success x " + data.x + ", y: " + data.y);
})
.error(function() { alert("error"); })
.complete(function(data) { });
}
function onUpdate(){
pos = getPos();
document.write("On Update: success x: " + arr[0] + ", y: " + arr[1] + "<br>");
}
function getP(){
setInterval("onUpdate()", 3000);
}
</script>
</head>
一切几乎都可以正常工作,但是一开始我没有收到该值-这是输出:
On Update: success x: undefined, y: undefined
On Update: success x: undefined, y: undefined
On Update: success x: 84366016, y: 1675639473
On Update: success x: 87449458, y: 139664776
On Update: success x: 980514625, y: 902346893
On Update: success x: -1435971236, y: -156758443
On Update: success x: -2095036525, y: -973261813
On Update: success x: -1304285873, y: 1260988577
On Update: success x: -1056490280, y: 1080724495
On Update: success x: -51836505, y: -706315772
On Update: success x: -358732800, y: -1112197198
On Update: success x: -638049254, y: 565725784
On Update: success x: -550065549, y: -851319836
On Update: success x: -2091397055, y: -1486304337
On Update: success x: -394112078, y: 671840086
On Update: success x: -1462169807, y: -567576336
On Update: success x: 2138172836, y: 1437950295
On Update: success x: -517824901, y: 1736496095
On Update: success x: -1129327909, y: 2010537838
On Update: success x: 1331271573, y: 1572909584
On Update: success x: -316422252, y: -2019877720
On Update: success x: 532846139, y: -1840296395
On Update: success x: -355252412, y: -866851861
On Update: success x: -276365039, y: 616559691
等等...
问题是 - 为什么前两行有“未定义”字样的值?在我的 Chrome 控制台中,我可以观察到两个第一个(和其余的)getJSON 请求的“200 OK”响应。也许我搞砸了一些价值观?提前谢谢任何帮助。