Thinkphp can't get AJAX post's data, but the simple problem is that it can't be solved.

thinkphp 5.0.7. Ajax is used in view to submit post data. After the data is submitted, it cannot be printed through tp.

After studying it for a long time, I really don"t know what went wrong.

A very simple test code,

Front end:


<html>
    <head>
        <title>title</title>
        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
        <script>
         $(function(){
            $("-sharpbtn").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>

Server side:

class Test extends Controller {

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

finally, the page output is:

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

here, the value of the id in the foreground, that is, $_ POST ["id"] is always null,

and the foreground alert (data.id); the content is also undefined.

in the contents of network, you can see the data of post and the success of post, but neither the front-end alert nor the background can get the data of post

What"s wrong with

?

May.22,2021

Today, I studied it for another day, and basically solved it.

The

problem mainly lies in print_r (json_encode () in the statement json_encode ($dd)); ).

in the PHP environment, there is no problem with using json_encode (), but in the thinkphp environment, using json_encode () will cause ajax post to fail,

in thinkphp, to disable json_encode (), you need to replace it with $this- > ajaxReturn ($array);

).

so that you can post successfully in the controller,

although the exact reason is not clear, it is true that this debugging is successful.

Menu