嗨,我正在使用cakephp为Android应用程序制作一个Web服务。我收到了请求,并且正在发送respose但是客户端的响应不可见。我的代码如下所示。可以有其他方法来发送响应。
public function AndroidApp() {
if (isset($_POST["myHttpData"])) {
$coupon = trim($_POST["myHttpData"]);
$couponId = $this->Code->find('all', array(
'conditions' => array(
'Code.coupon_code' => $coupon,
'Code.status' => 'Used'
),
'fields' => array('Code.id')));
$studentAssessmentId = $this->StudentAssessment->find('all', array(
'conditions' => array(
'StudentAssessment.code_id' => $couponId[0]['Code']['id'],
'StudentAssessment.status' => 'Complete'
),
'fields' => array('StudentAssessment.id')));
$scores = $this->AssessmentScore->find('all', array(
'conditions' => array(
'AssessmentScore.student_assessment_id' => $studentAssessmentId[0]['StudentAssessment']['id']
),
'fields' => array('AssessmentScore.score')));
$json = array();
$assessment_data = array();
//debug($scores);
$i = 0;
foreach ($scores as $score) {
$assessment_data[$i] = array("score" => $score['AssessmentScore']['score']);
$i+=1;
}
header('Content-type: application/json');
$json['success'] = $assessment_data;
$android = json_encode($json);
} else {
$json['error'] = "Sorry, no score is available for this coupon code!";
$android = json_encode($json);
}
echo $android;
答案 0 :(得分:0)
首先,如其他人的评论所述,您没有使用CakePHP请求/响应对象。因此,你过于复杂化了。请参阅此处的文档; http://book.cakephp.org/2.0/en/controllers/request-response.html http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
和
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
如果您将$scores
替换为find('all')
,并使用'score'作为显示字段,则重新格式化查询结果的find('list')
循环可能是多余的。请参阅此处的文档http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
您的代码中似乎也存在一些错误;
$_POST["myHttpData"]
存在时才会发送内容类型标头。$_POST["myHttpData"]
存在,而不是它是否实际包含任何数据(空)$couponId[0]['Code']['id']
存在(但如果未找到优惠券代码则不会)除了这些问题之外,您问题的最可能原因是您没有禁用“autoRender”。因此,CakePHP也会在您输出JSON后呈现视图,从而导致JSON响应格式错误。
public function AndroidApp() {
$this->autoRender = false;
// rest of your code here
}