我无法弄清楚为什么request.onreadystate函数内部的所有内容都可以运行,但是以下的alert()却没有。该脚本似乎在if语句之后中断。
我真的很感谢有人为我查看我的代码。非常感谢。
function positionHandler(position) {
if (!document.getElementById("span")) document.body.appendChild(document.createElement("span"));
document.getElementsByTagName("span")[0].innerHTML = "("+position.coords.latitude+","+position.coords.longitude+")";
request = new XMLHttpRequest();
request.asycnc = false;
request.open('GET','get.php?latitude='+position.coords.latitude+'&longitude='+position.coords.longitude);
request.onreadystatechange = function() {
if (request.readyState != 4) return false;
else if (request.readyState == 4 && request.status == 200) {
var results = request.responseXML.getElementsByTagName('note');
for (var i in results) {
if (!document.getElementById(results[i].getAttribute('id'))) {
var note = document.createElement('div');
note.innerHTML = results[i].childNodes[2].childNodes[0].nodeValue;
note.id = results[i].getAttribute('id');
document.getElementById('main').appendChild(note);
//everything up until this point works
}
}
alert("this doesn't work 1");
}
alert("this doesn't work 2");
}
request.send(null);
alert("this does work!");
}
var position = navigator.geolocation.watchPosition(positionHandler);
答案 0 :(得分:0)
尝试更改语句的顺序。
function positionHandler(position) {
if (!document.getElementById("span")) document.body.appendChild(document.createElement("span"));
document.getElementsByTagName("span")[0].innerHTML = "("+position.coords.latitude+","+position.coords.longitude+")";
request = new XMLHttpRequest();
request.asycnc = false;
// set the eventhandler logic
request.onreadystatechange = function() {
if (request.readyState != 4) return false;
else if (request.readyState == 4 && request.status == 200) {
var results = request.responseXML.getElementsByTagName('note');
for (var i in results) {
if (!document.getElementById(results[i].getAttribute('id'))) {
var note = document.createElement('div');
note.innerHTML = results[i].childNodes[2].childNodes[0].nodeValue;
note.id = results[i].getAttribute('id');
document.getElementById('main').appendChild(note);
//everything up until this point works
}
}
alert("this doesn't work 1");
}
alert("this doesn't work 2");
}
// the event will be triggered here
request.open('GET','get.php?latitude='+position.coords.latitude+'&longitude='+position.coords.longitude);
request.send(null);
alert("this does work!");
}
var position = navigator.geolocation.watchPosition(positionHandler);
原因是你在request.open(...)
语句调用后设置处理程序。
希望这有帮助。
答案 1 :(得分:-1)
这一行 - >警报(“这不起作用1”);不会起作用,因为循环可能是无限的。
这一行 - >警报(“这不起作用2”);仅在此条件else if (request.readyState == 4 && request.status == 200)
为假时才有效。
如果您修复了第一个警报问题,第三个警报应该有效。请检查你的循环。
最佳,