簡體   English   中英

讀取發布數據時 YII2 上出現 500(內部服務器錯誤)

[英]500 (Internal Server Error) on YII2 when reading post data

我想使用 ajax 將數據插入到帶有發布請求的表中,但我無法讀取我剛剛使用 ajax 發送的數據,這是我的代碼:

Ajax 代碼:

$('#newList').on('beforeSubmit', function(e){
e.preventDefault();
$("#newList").modal('hide');
$("#title").val("");
load(1);
$.ajax({
    url: '/site/add-list',
    type: 'post',
    data: {title : $("#title").val()},
    success: function(data) {
      console.log(data); // return 500 (Internal Server Error)
    }
});

});

Controller:

public function actionAddList()
{
    $req = Yii::$app->request;
    $newList = new Boards();
    return $req->post(); // return 500 (Internal Server Error)

}

每次我發送一個發布請求時,它都會在控制台上顯示 500(內部服務器錯誤)。 但是當我為 ex 返回一個字符串時。 “asdasd”它有效。 我該如何解決?

抱歉回復晚了,所以問題出在我的 controller 上,它應該看起來像這樣,以便 ajax 可以讀取我返回的值

public function actionAddList()
{
    $req = Yii::$app->request;

    if ($req->isAjax) {
        $res = ['data' => $req->post()];
        $newList = new Lists();
        $newList->title = $res["data"]["title"];
        $newList->save();
        echo $res["data"]["title"]; // Isnt error anymore
    } else {
        return false;
    }
    
}

我收到錯誤是因為我在 controller 上返回了一個數組,所以我只需要做這樣的事情

    // Bad
    return array(
        "data" => 'blabla'
    );

    // Good
    $dat = array(
        "data" => "blabla"
    );
    return $dat["data"];

我從控制台收到 500 錯誤的原因可能來自 YII 因為響應內容不能是數組。

if (is_array($this->content)) {
        throw new InvalidArgumentException('Response content must not be an array.');
    } elseif (is_object($this->content)) {
        if (method_exists($this->content, '__toString')) {
            $this->content = $this->content->__toString();
        } else {
            throw new InvalidArgumentException('Response content must be a string or an object implementing __toString().');
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM