我正在使用Yii作为使用REST API的移动应用程序的php后端。我可以看到客户端上的xhr数据对象包含正确的json编码值。我在我的模型类中设置了'safe'属性,如下所示:
array('user_id, last_visit, first_visit, blah, 'safe', 'on'=>'search')
插入符合预期。唯一的问题是除了自动递增的primay键之外,所有字段都会插入null
值。我几乎逐字地跟着这个有用的博客,Create a REST API,它的工作非常简单和好。我只是不知道如何调试空值插入。
我在客户端启动此方法
upload.open("POST", "http://localhost:8888/dashboard/index.php/api/tracker");
然后发送
upload.send(JSON.stringify(_xhrData));
然后在服务器上调用此方法:
public function actionCreate()
{
switch ($_GET['model']) {
// Get an instance of the respective model
case 'tracker':
$model = new Tracker;
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);
}
}
我没有错误,只是客户端上的以下状态消息
[INFO] {"user_id":"19","last_visit":null,"first_visit":null,"locale":null,"this_visit":null,"latitude":null,"longitude":null,"device_maker":null,"device_model":null,"os_platform":null,"os_version":null,"opted_out":null,"opted_in":null,"modified":null,"model_type":null}
我非常感谢有关调试的任何帮助。感谢。
答案 0 :(得分:0)
最可能的原因是您的数据未正确发布。尝试打印$ _POST并查看它返回的内容。
print_r($_POST);