【问题标题】:Ajax Call Sometimes Works, Sometime works and refreshes, Sometimes refreshes and fails …?Ajax 调用有时有效,有时有效并刷新,有时刷新但失败……?
【发布时间】: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


【解决方案1】:

您使用 jQuery ajax() 方法进行 ajax,它很容易理解并且可以正常工作

函数 post_positive(id){
$.ajax({
类型:'get',
网址:'post_review.php',
数据:{ 'id':id,'type':'positive' },
成功:函数(结果){
$("#post"+id).text(result);

                      }

           });
}

【讨论】:

    猜你喜欢
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多