【发布时间】:2011-12-21 12:32:19
【问题描述】:
目前我得到了这个代码:
function post_positive(id) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("post"+id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","post_review.php?id="+id+"&type=positive",true);
xmlhttp.send();
return false;
}
对于我的 ajax 调用,我只是函数 post_positive()。有时会显示结果,有时会刷新页面,有时什么也不会。
【问题讨论】:
-
您在哪个浏览器中看到了这种行为?
-
这里有问题的地方:1) 请正确缩进你的代码,这使得它更更容易调试 2) 缺少@987654323 @ 在
xmlhttp.onreadystatechange =声明的末尾 - 以这种方式声明函数是一个赋值 statement 并且因此需要在它的末尾加上一个分号 3) 你应该在使用它之前转义id在 URL 中(例如,escapeURIComponent())。除了这三件事之外,没有理由不能按预期工作 - 取决于现有的"post"+id元素,以及post_review.php的实际作用。 -
除了 DaveRandom 的答案之外,请检查 post_review.php 是否总是返回响应(不管是什么格式:文本、json、xml 等),因为我多次得到 500由于脚本的空响应而导致的错误,这就是导致 AJAX 失败的原因。
-
我错过了;但它仍然显示那些连接缓慢的奇怪东西,@Ignas post_review.php 总是发送数据,我使用的是 chrome 和 mozilla 都显示相同的输出
标签: php javascript ajax