gpt4 book ai didi

php - yii2访问post json数据出错

转载 作者:可可西里 更新时间:2023-11-01 00:00:02 43 4
gpt4 key购买 nike

我正在使用 ajax 请求将数据传递给 yii2,但我一直收到 500 错误

这是ajax请求代码:

<?php 
$script = <<< JS

$('form#forward_pr').on('beforeSubmit', function(e){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
error: function(err){
console.log("server error");
}
});
return false;
} ) ;

JS;
$this->registerJS($script);
?>

当我执行 console.log(keys) 时返回

[0, 1]

这是我的 Controller 代码:

if (Yii::$app->request->post()) {
echo $post = json_encode($_POST['keys']);
if (isset($_POST['keylist'])) {
$keys = \yii\helpers\Json::decode($_POST['keylist']);
print_r($keys);
}else{
echo "1";
}

上面一直执行post请求的error部分,可能是哪里出了问题;

最佳答案

您发送的 JSON 作为编码(发布)数据主体,而不是键值对。所以你的方法不是这样工作的。

有两个选项可以解决这个问题:

  1. 将您的 Controller 重构为 RESTful service
  2. 在您的 Controller 中使用 JSON 正文而不是 POST 参数

虽然从长远来看第一个选项是首选,但第二个选项作为快速修复非常简单。

首先,确保您将应用配置为解析 JSON 正文内容。在 config.php 中将此添加到 components 数组:

'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]

然后在您的 Controller 中使用它来获取 JSON 参数:

$model->load(Yii::$app->getRequest()->getBodyParams());

关于php - yii2访问post json数据出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38786511/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com