【问题标题】:ajax php call not returning anythingajax php调用不返回任何内容
【发布时间】:2014-02-18 15:37:33
【问题描述】:

我希望 php 向 ajax 返回一个值。我正在关注 W3 学校的例子,但并不高兴。 这是 javascript/ajax 代码:

function createReport() {
    var xmlhttp;    
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("report").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","test.php",true);
    xmlhttp.send();
}

我知道正在触发的事件处理程序中有以下调用(它所做的其他事情工作正常)

createReport();

后来在我拥有的 html 的正文部分:

<div id="report">Report will be placed here...</div>

如果我自己运行 test.php,它会正确显示“将其返回给 ajax”,所以我知道这是有效的。这是php代码:

<?php
echo 'return this to ajax';
?>

我的理解是“Report will be placed here...”将替换为“return this to ajax”。但什么也没有发生。我也没有在 Firefox 或 IE 控制台中看到任何错误。有什么想法吗?

【问题讨论】:

标签: javascript php ajax


【解决方案1】:
try{
    request = new XMLHttpRequest();
}catch(trymicrosoft){
     try{
        request = new ActiveXObject("Msxml2.XMLHTTP");
     }catch(othermicrosoft){
        try{
            request = new ActiveXObject("Microsoft.XMLHTTP");
       }catch(failed){
            request = false;
       }  
    }
}
if(!request)
{
    alert("Error initializing XMLHttpRequest!");
}

function Create_Ajax_Query(LinkToFile,Parametrs)
{
    window.document.body.style.cursor='progress';
    request = new XMLHttpRequest();
    var url = LinkToFile;
    var params = Parametrs;

    request.open("POST", url, true);    
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
    request.setRequestHeader("Content-length", params.length);
    request.setRequestHeader("Connection", "close");
    request.onreadystatechange = newinfo;
    request.send(params); 
 }

function newinfo() 
{
    if(request.readyState==4 && request.status == 200){
        window.document.body.style.cursor='default';
        alert(request.responseText);
    } 
}

希望它有用!

【讨论】:

    【解决方案2】:

    乍一看,我没有发现您的 js 代码有任何问题,所以我敢打赌,在您的文件夹结构中定位 test.php 可能是个问题。

    使用 firebug 检查您的 javascript AJAX 调用,并检查文件 test.php 是否被正确评估。

    【讨论】:

      【解决方案3】:

      我个人认为 w3cschools 不是一个学习的好地方(见http://www.w3fools.com/)。

      问题可能是因为你设置ajax的顺序,你做了:

      XMLHttpRequest/onreadystatechange/open/send

      更可取(如果不遵循此顺序可能会在旧浏览器中出现几个缺陷):

      XMLHttpRequest/open/onreadystatechange/send

      注意:不用担心,“open(...)”不会启动监听器。 监听器只在“send(...)”之后工作

      另一个原因可能是您没有创建XMLHttpRequest.status 的“错误处理”,它用于验证服务器响应中的错误。

      试试这个:

      <script>
      function XHR(){
          if(window.XMLHttpRequest){//outers browsers
              return new XMLHttpRequest();
          } else if(window.ActiveXObject){//IE
              try{
                  return new ActiveXObject("Msxml2.XMLHTTP");
              } catch(ee) {//IE
                  try{
                      return new ActiveXObject("Microsoft.XMLHTTP");
                  } catch(ee) {}
              }
          }
          return false;
      }
      
      function createReport(){
          var xhr = XHR();// call ajax object
          if(xhr){
              xhr.open("GET", "test.php", true);//setting request (should always come first)
              xhr.onreadystatechange = function(){//setting callback
                  if(xhr.readyState==4){
                      if(xhr.status==200){
                          document.getElementById("report").innerHTML=xhr.responseText;
                      } else {//if the state is different from 200, is why there was a server error (eg. 404)
                          alert("Server return this error: " + String(xhr.status));
                      }
                  }
              };
              xhr.send(null);//send request, should be the last to be executed.
          } else {
              alert("Your browser no has support to Ajax");
          }
      }
      </script>
      
      <div id="report">Report will be placed here...</div>
      
      <script>
      createReport();//prefer to call the function after its div#report
      </script>
      

      为了防止缓存,替换:

      xhr.open("GET", "test.php", true);

      xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);

      【讨论】:

      • “w3schools”那个地方根本不应该存在。
      • @JorgeFaianca 谢谢。
      • 我不是说你的错字,我很高兴你打错字了,我的意思是,“w3schools”不应该存在,它很糟糕,没有人应该从那个网站学习。
      • is preferable: xhr, open , onreadystatechange and send. 不。正确的方法是在打开链接之前放置监听器。尽管这看起来是程序性的,但即使之后打开,听众也会听。我在每个 ajax 调用中都使用 op 的顺序,这从来都不是问题。这家伙解释得更好:stackoverflow.com/questions/16848955/…
      • @FélixGagnon-Grenier 原因是某些浏览器出现故障,请注意“onreadystatechange”仅在“send()”之后开始工作,然后“open/onreadystatechange”或“onreadystatechange/open”会不改变任何东西。但问题是一些较旧的浏览器,例如。 IE7(就像你发给我的链接一样)。无论如何,谢谢,分享经验很酷
      【解决方案4】:

      在测试了下面的代码(从他们的网站上提取)之后,我没有发现 W3Schools 的 Ajax 示例有任何问题。

      • 可能的因素:

        1. 缺少&lt;script&gt;&lt;/script&gt; 标签

        2. 确保您已启用 JS。

        3. 确保您的浏览器支持它。

        4. 您可能忘记将按钮的调用更改为正确的函数。

      使用 FF 26.0 和 IE 版本 7 的工作和测试代码

      W3 Schools Website (example) 中提取并稍作修改以证明这是可行的。

      点击Change Content按钮时的结果:

      return this to ajax - 根据您的 PHP 代码。

      <!DOCTYPE html>
      <html>
      <head>
      <script>
      function loadXMLDoc()
      {
      var xmlhttp;
      if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
      else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
          document.getElementById("report").innerHTML=xmlhttp.responseText;
          }
        }
      xmlhttp.open("GET","test.php",true);
      xmlhttp.send();
      }
      </script>
      </head>
      <body>
      
      <div id="report"><h2>Let AJAX change this text</h2></div>
      <button type="button" onclick="loadXMLDoc()">Change Content</button>
      
      </body>
      </html>
      

      使用的 PHP: (test.php)

      <?php
      echo 'return this to ajax';
      ?>
      

      • 其他可能的因素:

        1. 如果在local 机器上,您的服务器不支持 PHP 或未正确解析 PHP,或者未正确安装或配置。
        2. 如果在托管服务上,请确保 PHP 可供您使用。
        3. 文件与执行文件不在同一个文件夹中。

      【讨论】:

      • 我完全复制了这个并将其放入一个新文件并上传到服务器。你是对的,它确实有效!仍然无法让它在我的代码中工作,所以我做错了。这大大缩小了我的搜索范围。现在寻找差异......是的,我有脚本标签。
      • 你为什么不使用我的代码并用你拥有的 createReport() 替换所有 loadXMLDoc() 实例? @user3217883 - 基本上是plug &amp; play ;-)
      • 我现在也在IE 7 上测试了它,它也适用于那个浏览器。 @user3217883 - 您使用的是哪个浏览器和版本?并确保您的 div id 匹配。
      • 取得任何进展? @user3217883
      • 抱歉,电话打得太久了……我添加了以下代码以确保没有文件夹问题:alert('im in createReport'); xmlhttp.open("GET","virtualhuman.tekknow.net/test.php",true); xmlhttp.send(); alert('back from send'); 两个警报都显示了,但 div id=report 仍然没有改变其内容
      【解决方案5】:

      代码看起来正确。它在本地环境中运行得很好。 我建议查看开发人员工具中的“网络”选项卡,以检测服务器端可能发生的任何错误。您也可以使用 console.log() 来跟踪 javascript 的实际流程:

      function createReport() {
          var xmlhttp;    
          if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
          }
          else {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
          xmlhttp.onreadystatechange=function() {
              console.log(xmlhttp); //to show the entire object after statechage.
              console.log(xmlhttp.readyState); //to show specific parameter.        
      
              if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                  document.getElementById("report").innerHTML=xmlhttp.responseText;
              }
          }
          xmlhttp.open("GET","test.php",true);
          xmlhttp.send();
      } 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-25
        • 2020-01-27
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        相关资源
        最近更新 更多