如何在Zend框架2的宁静实现中获取更新中的$ data($ id,$ data)
在邮差中,我正在尝试发送..
{
"gender":"1",
"country":"1",
"state":"2",
"city":"23",
"address1":"27,djkfhasdkjh,kjsdfhdkjs,kjsdh",
"address2":"ksjadh f,sdkjfhjk",
"postal_code":"627811",
"birthdate":"11-12-2045",
"phone":"0442805565",
"mobile":"9865521557",
"blood_group":"o-",
"weight":"60",
"height":"5.2",
"bmi":"10",
}
我的休息代码是:
// update :: update 公共功能更新($ id,$ data){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
$data = json_decode($data);
print_r($data);
if(empty($data)){
$resp = array('status' => 'failure', 'errorCode' => 516, 'errorMessage' => 'json code format error');
return new JsonModel($resp);
}
if ((strlen($data->mobile) >= 10) && (is_numeric($data->mobile))) {
}
else{
$resp = array('status' => 'failure', 'errorCode' => 517, 'errorMessage' => 'mobile validation error');
return new JsonModel($resp);
}
if(($data->gender == '1') || ($data->gender == '2')){
}
else{
$resp = array('status' => 'failure', 'errorCode' => 517, 'eerorMessage' => 'gender validation error');
return new JsonModel($resp);
}
$id = $this->params('id');
$sm = $this->getServiceLocator();
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$usersService = new UsersService($dbAdapter);
$resp = $usersService->update($data,$id);
$resp = array('status' => 'success');
return new JsonModel($resp);
exit;
谢谢,
答案 0 :(得分:2)
在您的情况下(PUT
请求映射到update
方法),AbstractRestfulController
将从processBodyContent
方法获取数据on line 419
此方法将使用requestHasContentType
方法检查正确的内容类型(application/json
)。因此,如果您将请求中的Content-Type
标头设置为application/json
,则应自动填充控制器中的$data
变量。
所以在你的邮递员中确保你设置了Content-Type
标题:
注意:您不必须自己解码 json数据,这是在控制器中处理的。
答案 1 :(得分:-1)
class MyController extends AbstractRestfulController
{
public function update($id, $data)
{
var_dump($id, $data);
}
}
将JSON发送到url ... / mycontroller / 1
{"数据":" 15"}
方法PUT
Content-Type:application / json
output:
array(1, 'data' => 15);