gpt4 book ai didi

json - Yii Restful API 将在 POST 上创建但不填充任何变量

转载 作者:行者123 更新时间:2023-12-04 04:45:25 25 4
gpt4 key购买 nike

您好,我目前正在尝试使用 POSTMAN 来测试基于这篇文章的早期 API
http://www.yiiframework.com/wiki/175/how-to-create-a-rest-api/

尝试通过 POST 以 php url 样式提交变量甚至发送对象时出现错误。来自 API 的响应返回 200 并在数据库中创建一个新条目,但不幸的是它不会从 post 变量或 jason 对象中获取任何信息,它只是出现空值。现在看来,该代码只是查看 $_POST 变量并尝试将它们与模型变量匹配,如果是这样,它应该更新它并保存它,但是当我尝试通过 POSTMAN 中的 url 参数发送甚至更改内容类型时json 并发送原始 json 对象我似乎没有运气。

此外,我真的只需要它来解码 jason 对象而不是 post 参数,所以也许这就是我将通过删除 $post 循环并着手检索 JSON 对象开始的地方。感谢您的帮助!

public function actionCreate()
{
switch($_GET['model'])
{
// Get an instance of the respective model
case 'event':
$model = new Event;
break;
case 'media':
$model = new Media;
break;
case 'comment':
$model = new Comment;
break;
default:
$this->_sendResponse(501,
sprintf('Mode <b>create</b> is not implemented for model <b>%s</b>',
$_GET['model']) );
Yii::app()->end();
}
// Try to assign POST values to attributes
foreach($_POST as $var=>$value) {
// Does the model have this attribute? If not raise an error
if($model->hasAttribute($var))
$model->$var = $value;
else
$this->_sendResponse(500,
sprintf('Parameter <b>%s</b> is not allowed for model <b>%s</b>', $var,
$_GET['model']) );
}
// Try to save the model
if($model->save())
$this->_sendResponse(200, CJSON::encode($model));
else {
// Errors occurred
$msg = "<h1>Error</h1>";
$msg .= sprintf("Couldn't create model <b>%s</b>", $_GET['model']);
$msg .= "<ul>";
foreach($model->errors as $attribute=>$attr_errors) {
$msg .= "<li>Attribute: $attribute</li>";
$msg .= "<ul>";
foreach($attr_errors as $attr_error)
$msg .= "<li>$attr_error</li>";
$msg .= "</ul>";
}
$msg .= "</ul>";
$this->_sendResponse(500, $msg );
}
}

最佳答案

通过删除 $POST 循环并仅更改为 JSON 对象方案来修复。如果有人碰巧发现自己处于这种情况,这里是代码。

//read the post input (use this technique if you have no post variable name):
$post = file_get_contents("php://input");

//decode json post input as php array:
$data = CJSON::decode($post, true);

//load json data into model:
$model->attributes = $data;

通过 $_POST 变量使用它而不是 foreach 循环。现在它接受一个 json 对象。祝大家编码愉快!

关于json - Yii Restful API 将在 POST 上创建但不填充任何变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280967/

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