我使用yii作为使用rest api的移动应用程序的php后端。我可以看到客户端上的xhr数据对象包含正确的json编码值。我在模型类中设置了“safe”属性,如下所示:
array('user_id, last_visit, first_visit, blah, 'safe', 'on'=>'search')
插入物按预期发生。唯一的问题是
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}
我将非常感谢任何帮助调试这个。谢谢。
最佳答案
最可能的原因是您的数据没有正确发布。试着打印$并查看它返回的内容。
print_r($_POST);