繁体   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