2017-07-21 115 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是如何幫助我的。就你的評論而言,我甚至用引號試過,但我得到了同樣的錯誤。 –

相關問題