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

Asa*_*ran 4 php ajax jquery

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

  1. 该脚本有一个输入按钮来调用AJAX调用.
<input type="button" id="btn" />
Run Code Online (Sandbox Code Playgroud)
  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}
    
    
        }); 
        }); 
    });
    
    Run Code Online (Sandbox Code Playgroud)
  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(); 
     }
    
    Run Code Online (Sandbox Code Playgroud)

问题:

此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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Mag*_*gus 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(); 
}
Run Code Online (Sandbox Code Playgroud)

如果要响应json,则必须将其放在响应内容中.在Php中,您只需使用echo在响应内容中添加内容即可.