0

嗨,我正在为一个 Android 应用程序在 cakephp 中创建一个 Web 服务。我收到请求并且正在发送响应,但响应在客户端不可见。我的代码如下所示。是否有其他方法可以发送响应。

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;
4

1 回答 1

0

代码异味,非 cakephp 标准

首先,正如其他人在评论中提到的,您没有使用 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

如果您将 'score'替换为显示字段,则重新格式化查询结果的$scores循环可能是多余的。请参阅此处的文档http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-listfind('all')find('list')

错误

您的代码中似乎也存在一些错误;

  • $_POST["myHttpData"]仅在存在时才发送内容类型标头。
  • 您只检查是否$_POST["myHttpData"]存在而不是检查它是否实际包含任何数据(空)
  • 没有检查各种查询是否返回结果。如果查询没有返回任何内容,这将导致您的代码出错!例如,您假设存在$couponId[0]['Code']['id'](但如果未找到优惠券代码,则不会存在)

可能的答案

除了这些问题之外,问题的最可能原因是您没有禁用“自动渲染”。因此,CakePHP 也会在您输出 JSON 后呈现视图,从而导致格式错误的 JSON 响应。

public function AndroidApp() {
     $this->autoRender = false;

     // rest of your code here

}
于 2013-03-15T23:17:55.390 回答