我正在開發一個單頁腳本,即類別管理的category.php。Php Ajax調用相同的PHP腳本響應null
- 該腳本有一個輸入按鈕來調用AJAX調用。
<input type="button" id="btn" />
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} }); }); });
用於招待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(); }
問題:
這Ajax調用是無法產生螢火控制檯回調函數正確的反應,並導致錯誤。 類型錯誤:數據爲空
在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
一個良好問的問題 – 2013-03-26 13:04:14
如說,忘了響應(使用echo) 也HTTP_X_REQUESTED_WITH是不檢測Ajax請求(最重要的是在jQuery的情況下) – vladkras 2013-03-26 13:19:40