Symfony ajax响应,但带有标题:HTTP/1.0 200 OK缓存控制:无缓存日期


Symfony ajax Response but with headers: HTTP/1.0 200 OK Cache-Control: no-cache Date

我遇到了Symfony和ajax调用的问题。

我在Windows 8上的本地服务器上使用XAMPP 1.8.2。

每一个都很好,但当我得到回应时,我有这个,在右边的文本下面:

HTTP/1.0 200 OK Cache-Control: no-cache Date: Tue, 19 Nov 2013 14:58:18

为什么?

我的代码:

在底部的HTML(Twig)中:

$.ajax({
url: "{{ path('score') }}",
data: { id: scoreid, value: value },
dataType: 'json',
type: 'POST',
success: function (data) {
    if(data.responseCode==200 ){           
    $('#score').html(data.score);
    $('#score').css("color","green");
            }
else if(data.responseCode==400){
    $('#score').html(data.score);
    $('#score').css("color","red");
     }
     else{
    alert("An unexpeded error occured.");
    $('#score').html(data);
      }
            },
  error: function (jxhr, msg, err) {
    $('#score').html('<span style="color:red">Error!</span>');
     }
});

控制器"分数":

class scoreController extends Controller
{
    public function onepointAction(Request $request) {
        ....some logical...
            $points = self::pointsAction($id);
            $return=array("responseCode"=>200, "score"=>"Score: ".$num.".", "goal"=>"".$points);
        }
        else {
            $return=array("responseCode"=>400, "score"=>"No good!");
        }
        $return = json_encode($return);
        return new Response($return,200,array('Content-Type'=>'application/json'));
    }
    public function pointsAction($id) {
        ......some logical query... ended by:
            ->getQuery();
        $pointsOk = $query->getResult();
        $avgScore = $avgScore[0]["score_avg"];
        $numScore = $avgPoints[0]["score_count"];
        $points = ("Scores: ".$avgScore."Goals: ".$numScore);
        return new Response($points);
    }
}

我在哪里出错?

我找到了解决我的大问题的方法:

$points末尾的->getContent()=self::pointsAction($id);

这很正常,因为您正在渲染一个完整的"Response"对象,其中也包含标头。

你所看到的

HTTP/1.0 200 OK Cache-Control: no-cache Date: Tue, 19 Nov 2013 14:58:18

是包含在控制器应答中的标头。

如果您想直接呈现JSon,那么应该考虑使用JSonResponse对象,而不是Response对象。(FQCN:Symfony'Component'HttpFoundation'JsonResponse

为了澄清,这就是他的意思:

return response()->json([
            'status' => $status,
            'message' => $message,
        ], 200)->getContent();