我只是Slim框架中的新手。我已经使用Slim框架编写了一个API。
iPhone应用程序将向此接口发出POST请求。此POST请求为JSON格式。
但是我无法访问从iPhone请求中发送的POST参数。当我尝试打印POST参数的值时,我得到的每个参数都是"null“。
$allPostVars = $application->request->post(); //Always I get null然后,我尝试获取即将到来的请求的正文,将正文转换为JSON格式,并将其作为对iPhone的响应发送回来。然后我得到了参数值,但它们的格式非常奇怪,如下所示:
"{\"password\":\"admin123\",\"login\":\"admin@gmail.com\",\"device_type\":\"iphone\",\"device_token\":\"785903860i5y1243i5\"}"所以有一件事是肯定的,那就是POST请求参数将传入此API文件。虽然它们在$application->request->post()中不可访问,但它们正在进入请求正文。
我的第一个问题是如何从请求体访问这些POST参数,我的第二个问题是为什么在将请求体转换为JSON格式后,请求数据会显示为上面这样奇怪的格式?
以下是必要的代码片段:
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$body = $application->request->getBody();
header("Content-Type: application/json");//setting header before sending the JSON response back to the iPhone
echo json_encode($new_body);// Converting the request body into JSON format and sending it as a response back to the iPhone. After execution of this step I'm getting the above weird format data as a response on iPhone.
die;
?>发布于 2015-01-22 01:49:20
一般来说,您可以通过以下两种方式之一单独访问POST参数:
$paramValue = $application->request->params('paramName');或
$paramValue = $application->request->post('paramName');文档中提供了更多信息:http://docs.slimframework.com/#Request-Variables
当在POST中发送JSON时,您必须访问请求体中的信息,例如:
$app->post('/some/path', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
// do other tasks
});发布于 2016-01-12 16:18:30
"Slim可以解析JSON、XML和URL编码的开箱即用的数据“- http://www.slimframework.com/docs/objects/request.html在”请求主体“下面。
处理任何主体形式的请求的最简单方法是通过"getParsedBody()“。这将是guillermoandrae示例,但在1行而不是2行。
示例:
$allPostVars = $application->request->getParsedBody();然后,您可以通过给定数组中的键来访问任何参数。
$someVariable = $allPostVars['someVariable'];https://stackoverflow.com/questions/28073480
复制相似问题