Php ajax调用相同的php脚本响应null

时间:2013-03-26 13:03:14

标签: php jquery ajax

我正在开发单页脚本,即category.php进行类别管理。

  1. 此脚本有一个输入按钮,用于调用AJAX调用。
  2. <input type="button" id="btn" />
    
    1. 用于绑定click事件并调用ajax的Jquery代码。我想要json的回应。

      $(document).ready(function(e) {
      $('#btn').click(function(e) {
              id=1;
              jQuery.ajax({
              type: 'post',
              url: 'category.php',
              success: function(data) {
                  if(data.rstatus==1){
                  alert(data.text);   
              }else
              alert(data);
          },
              data:{'id':id}
      
      
          }); 
          }); 
      });
      
    2. 用于娱乐AJAX呼叫的PHP代码。

      if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
          $jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
          header("Content-type: application/json");   
          json_encode($jsonResponse);
          die(); 
       }
      
    3. 问题:

      这个ajax调用无法在回调函数中产生正确的响应,并导致firebug控制台出错。 TypeError:data为null

      在FIREBUG标题如下:

        

      Response Headers

      > Cache-Control no-cache, must-revalidate Connection    Keep-Alive
      > Content-Length    0 Content-Type  application/json Date   Tue, 26 Mar 2013
      > 12:45:52 GMT Expires  Mon, 26 Jul 1997 05:00:00 GMT
      > Keep-Alive    timeout=5, max=98 Last-Modified Tue, 26 Mar 2013
      > 12:45:52GMT Pragma    no-cache Server Apache/2.4.3 (Win32) OpenSSL/1.0.1c
      > PHP/5.4.7 X-Powered-By    PHP/5.4.7
      
        

      Request Headers

      > > Accept  */* Accept-Encoding gzip, deflate
      >     > Accept-Language en-US,en;q=0.5 Content-Length   4
      >     > Content-Type    application/x-www-form-urlencoded; charset=UTF-8
      >     > Cookie  __gads=ID=39701a3d85dce702:T=1350383638:S=ALNI_MY_rHGVQ-qNxH4UGmbY_G-IuVcDkA;
      >     > __utma=141011373.593047819.1350426838.1364292528.1364295112.314;PHPSESSID=1s73cho6ildjt80jtudt8nq0f5 Host   abc.com Referer http://www.abc.com/category.php
      >     > User-Agent  Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101
      >     > Firefox/19.0 X-Requested-With   XMLHttpRequest
      

3 个答案:

答案 0 :(得分:8)

看起来你的回复内容是空的。你忘记了echo

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
    header("Content-type: application/json"); 
    echo json_encode($jsonResponse); 
    die(); 
}

如果要响应json,则必须将其放在响应内容中。在Php中,您只需使用echo将某些内容放入响应内容中。

答案 1 :(得分:0)

这并不简单,因为$_SERVER不包含该信息。所有请求标头都没有真正存储在那里。请查看getallheadershttp://php.net/manual/en/function.getallheaders.php

编辑:哦,你也需要回应回应。 $ _SERVER可能包含您在这种情况下所需的信息,但它不可靠且便携。我仍然建议你使用getallheaders

答案 2 :(得分:0)

不要使用HTTP_X_REQUESTED_WITH - 几乎不适用于jQuery 尝试发送额外的var,比如

data:{'id':id,'request':'xmlhttprequest'}