鍍金池/ 問答/PHP/ Thinkphp無法獲得AJAX post的數(shù)據(jù),很簡單的問題就是無法解決?

Thinkphp無法獲得AJAX post的數(shù)據(jù),很簡單的問題就是無法解決?

thinkphp 5.0.7 ,view里使用ajax提交post數(shù)據(jù),數(shù)據(jù)提交后,無法通過tp打印出來。

研究了好久,實在搞不清是什么地方出問題了。

一個很簡單的測試代碼,

前端:


<html>
    <head>
        <title>title</title>
        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
        <script>
         $(function(){
            $("#btn").click(function(){
              
              
                $.ajax({
                    url:"/Home/test/index",
                   type: "POST",
                    dataType:"",
                    data:{id:3},
                    //async: false,
                    success:function(data){
                       
                    
                       alert(data.id);
                    }
                    
                    
                });
                
            });
        });
        </script>
    </head>
    <body>
        <input type="button" id="btn" value="button">
    </body>
</html>

服務(wù)器端:

class Test extends Controller {

        public function index()
        {
         
            $dd['id'] = $_POST['id'];
           
            $dd['value'] = 'fff';
            print_r(json_encode($dd));
            
            return $this->fetch();
     
    }

最后,頁面輸出內(nèi)容是:

{"id":null,"value":"fff"} 

這里,前臺的id的值,也就是$_POST['id'] 始終是null,

而且前臺alert(data.id); 出來的內(nèi)容也是undefined。

network里面的內(nèi)容,可以看到post的數(shù)據(jù)和post成功,但是在前端alert和后臺都獲取不到post的數(shù)據(jù)

圖片描述

是什么地方出問題了呢。

回答
編輯回答
安若晴

今天又研究了一天,基本解決了。

問題主要是出在print_r(json_encode($dd)); 這條語句中的json_encode()上。

在PHP環(huán)境中,使用json_encode()完全沒有問題,但是在thinkphp環(huán)境下,使用json_encode()就會導(dǎo)致ajax post失敗,

在thinkphp中,要禁止使用json_encode(),而需要換成 $this->ajaxReturn($array);

這樣就可以在控制器中post成功,

雖然具體原因不清楚,但是確實這樣調(diào)試成功了。

2017年12月22日 19:25