2017-07-21 118 views
-3

当我将请求类型设置为“GET”(并且在服务器端也使用$ _GET)时,它成功获取响应 ,但给出一个400 error,Missing required parameters: student_id当我将类型设置为POST。为什么在请求方法为GET时此ajax请求成功但在POST方法中失败

下面的代码:

$.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);  
     } 
}); 

这是当我设置请求方法为GET请求URL:

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

为什么当我将上面的请求类型设置为POST并通过POST方法接收服务器端的变量时,这不起作用?

这里是服务器端操作(我用Yii2 MVC框架)

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

} 
+0

downvoter,关心评论? –

+0

如何在$ _POST中获得$ _GET方法参数? –

+0

如果你不知道方法是$ _GET还是$ _POST –

回答

2

您的功能需要参数$student_idGET方法。如果您使用AJAX发送请求,使用data: { 'student_id': student_id }, - 它将被添加到您的发送AJAX的URL。

如果你想使用POST方法,你必须修改网址:

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

,并删除data关键。

第二种方法是从你的actionTransactions,那么系统中删除$student_id PARAM将接受请求,而在GET$student_id,但是你必须保证,那它在$_REQUEST

+0

虽然答案有点迟,因为我已经知道了,这绝对是一个完整的解决方案。另外,你不认为这个问题值得赞赏吗?如果您确实请注意,因为我个人认为我尽力清楚和完整地描述可以复制的问题。关于这方面的文档也不常见,至少我找不到。 –

-1
$.ajax({ 
    type: "GET/POST", 
    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);  
    } 

});

你错过了student_id,引用'student_id'。干杯。

+0

,不会改变任何东西。它应该工作,即使当student_id没有引用 –

+0

@RameshPareek它确实改变了事情,而不是引用的变量的值,它现在使用了一个字符串'student_id',这是你发布的端点的关键*应该*尝试读书。这也是您的端点出现此错误的原因:“缺少必需的参数:student_id”。 我诚实地认为你应该少一点粗鲁,人们试图在这里免费帮助你。 – iSidle

+0

@iSidle,我不明白downvoting是如何帮助我的。就你的评论而言,我甚至用引号试过,但我得到了同样的错误。 –

相关问题