使用AJAX调用从Symfony2控制器返回JSONP [英] Returning JSONP from Symfony2 controller using AJAX call

查看:59
本文介绍了使用AJAX调用从Symfony2控制器返回JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Symfony2返回JSONP.我可以很好地返回常规JSON响应,但似乎JSON响应类正在忽略我的回调.

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');
        }
        });   

然后在我的控制器中:

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

我从中得到的响应始终是常规JSON.没有回调包装.

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

Json Response类在这里:

The Json Response class is here:

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

推荐答案

如文档所述:

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

您正在将回调方法设置为$headers参数.

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

所以您需要:

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

这篇关于使用AJAX调用从Symfony2控制器返回JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆