douzhenggui8171
2017-07-21 12:50
浏览 234
已采纳

当请求方法是GET但在POST方法中失败时,为什么这个ajax请求成功

When I set the request type to "GET",(and also use $_GET on server side), it successfully fetches the response, but gives a 400 error, Missing required parameters: student_id when I set the type to POST.

Here's the code :

$.ajax({
        type: "GET",
        url: "?r=fees/fees/transactions",
        dataType: "json",
        data: { student_id: student_id },           
        success:function( msg ) { 
            console.log(msg);
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log("failed");
            console.log(xhr.responseText);
            console.log(ajaxOptions);
            console.log(thrownError);    
        }
});

Here is the request URL when I set the request method to GET:

http://localhost/demo.git/index.php?r=fees/fees/transactions&_csrf=bEJJWVowdl8jBwQjaUMsAA52eT8MXBMLJigwHTxeKSlVKyxoD2o5KQ%3D%3D&student_id=10115".

why doesn't this work when I set the above request type to POST and receive the variable on server side by POST method?

Here is the server side action (I am using Yii2 MVC framework)

public function actionTransactions($student_id){
    $student_id = $_POST['student_id'];
        ...
        ...   
    echo json_encode($response);

}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxieti6851 2017-07-21 14:55
    已采纳

    Your function need param $student_id from GET method. If youre using AJAX to send request, using data: { 'student_id': student_id }, - it will be added to your URL where AJAX is sent.

    If you want to use POST method, you have to modify your URL:

    url: "?r=fees/fees/transactions?student_id=" + student_id,
    

    And remove data key.

    Second solution is to remove $student_id param from your actionTransactions, then system will accept requests without $student_id in GET, but you will have to ensure, that it's in $_REQUEST.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题