2

My Ajax call:

$.ajax({
    url : path,
    type: 'POST',
    dataType : 'json',
    data: data,
    success: function(memberExtra) {
        console.log (memberExtra);
    }
});

My response:

HTTP/1.0 201 Created
Cache-Control: no-cache
Content-Type:  application/json
Date:          Tue, 10 Feb 2015 23:49:09 GMT

{"memberExtras":{"label":"seller","dropdown":"abc"}}

My PHP:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Update the pulldown menus.
 *
 * @Route("/classification", name="classification")
 * @Template()
 */
public function classificationAction(Request $request)
{
    $memberType = $request->request->get('classification');

    $label = $memberType["user"]["memberType"];
    $dropdown = "abc";
    $response = new Response(json_encode(array('memberExtras' => array(
        'label' => $label,
        'dropdown' => $dropdown,
    ))), Response::HTTP_CREATED);
    $response->headers->set('Content-Type', 'application/json');

    return new Response($response);
}

The console.log doesn't output anything. Even if a regular text expression like ("test").

If I remove the dataType : 'json' declaration and attempt to manually parse the data via $.parseJSON(memberExtra), I get this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Not too surprised. Basically, it seems that the parser gets tripped on the header returned by the Symfony class. How can I avoid this header and just get to the JSON?

Thanks!

4

2 回答 2

0

尝试简单:

return $response;

而不是返回

new Response($response);

顺便说一句,我建议你简单地使用

return new JsonResponse($myarray) 

并从您的方法中删除注释 @Template。

希望这有帮助

于 2015-02-11T14:10:27.247 回答
0

替换return new Response($response);return $response;

基本语法:

$response = new Response();

$response->setContent(json_encode(array(
    'id' => $entity->getId(),
    'other' => $entity->getOther(),
)));

$response->headers->set('Content-Type', 'application/json');

return $response;
于 2015-02-11T14:09:49.833 回答