AJAX JQuery JSON Post Data not Reaching Controller

2020-07-27 02:02发布

var url =  base_url+"ajax/user/list_user_info/"+userId;
$.ajax({
        type: "POST",
        url: url,
        data:{user_id:userId},
        contentType: 'application/json',
        dataType: 'JSON',
        success: function(data) {

            if(data.redirect){
                window.location = data.redirect;    
            }
            else {
                $('#profile-main-content').html(data.html);
            }    
        }      
    });

Now, this is my request, a pretty standard AJAX request. My problem is that this request is not reaching the controller for some reason. To check I have performed a simple test insert in the database to check the result at first line of the controller's function. But the test does not get inserted. The url is correct because i checked the declaration of the base_url. I know I put the "userId" as an argument and passed it as POST data, but this is me just trying desperately. Any Ideas please? Let me know if i was not clear about anything. Thanks.

1条回答
够拽才男人
2楼-- · 2020-07-27 02:28

Instead of:

data:{user_id:userId}

try:

data: JSON.stringify({user_id:userId})

The reason for this is that you specified a request content type of application/json so you need to send JSON. In your code you are not sending a JSON request - you are sending a simple application/x-www-form-urlencoded POST request. And since you have already passed the userId in the POST body you probably don't need to repeat it in your url. Use either one or the other method to send this information to your server.

Also in order to more easily debug javascript errors I strongly suggest you to use FireBug. Among many things it allows you to see the exact requests/responses being sent during an AJAX call and analyze the exact error message you are getting from the server. It makes debugging problems much easier.

查看更多
登录 后发表回答