Returning JSONP from Symfony2 controller using AJAX call

依然范特西╮ 提交于 2019-12-07 13:40:25

问题


I'm trying to return JSONP from Symfony2. I can return a regular JSON response fine, but it seems as if the JSON response class is ignoring my callback.

$.ajax({
        type: 'GET',
        url: url,
        async: true,
        jsonpCallback: 'callback',
        contentType: "application/json",
        dataType: 'jsonp',                      
        success: function(data) 
        {                                   
              console.log(data);
        },
        error: function() 
        {
            console.log('failed');
        }
        });   

Then in my controller:

$callback = $request->get('callback');    
$response = new JsonResponse($result, 200, array(), $callback);
return $response;

The response I get from this is always regular JSON. No callback wrapping.

The Json Response class is here:

https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php


回答1:


As the docs says:

$response = new JsonResponse($result, 200, array(), $callback);

You're setting the callback method as the $headers parameter.

So you need to:

$response = new JsonResponse($result, 200, array());
$response->setCallback($callback);
return $response;



回答2:


The JsonResponse's constructor doesn't take the callback argument. You need to set it via a method call:

$response = new JsonResponse($result);
$response->setCallback($callback);

return $response;


来源:https://stackoverflow.com/questions/12670803/returning-jsonp-from-symfony2-controller-using-ajax-call

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!