如何在cakephp 2.4中实现JsonP [英] how to implement JsonP in cakephp 2.4

查看:78
本文介绍了如何在cakephp 2.4中实现JsonP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚升级到cakephp 2.4.1,因为它现在支持JsonP。我以前在我的Ajax跨域代码中遇到丢失的回调错误。但是,文档中没有提到实现此操作所需的任何其他步骤,因此我本以为应该这样做,但是却收到与以前相同的错误。

I have just upgraded to cakephp 2.4.1 as it now supports JsonP. I was previously getting an a missing callback error in my ajax cross domain code. However the documentation does not mention any additional steps need to implement this so I would have thought that it should wold but i get the same error as before.

我是否需要一个

我的控制器

public function api($mem_id = null) {
    $options = array(
        'fields' => array('Member.total_points'),
        'conditions' => array('Member.member_no' => $mem_id),
        'recursive' => -1
    );
    $members = $this->Member->find('first', $options);
    $this->set(array(
        'member' => $members,
        '_serialize' => array('member')
    ));
}

}

ajax代码

$('document').ready(function() {
    $.ajax({
        url: 'http://mydomain.com/loyalty/members/api/5749.json',
        dataType: 'jsonp',
        success: function(response) {
            console.log(resonse);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
});


推荐答案

它也应该在较旧的Cake版本上也能正常工作,就像我在另一个问题中所描述的那样;)

It should have worked fine with the older Cake version too, just as I've described in your other question ;)

无论如何,请查看 /lib/Cake/View/JsonView.php API文档中。您必须定义一个名为 _jsonp 的视图变量,该变量可以是一个字符串,它指定保存回调函数名称的查询变量的名称,或者是 true 表示正在查找名称为 callback 的默认查询变量。

Anyways, look at the code in /lib/Cake/View/JsonView.php or in the API documentation. You have to define a view var named _jsonp, which can be either a string specifying the name of the query variable that holds the callback function name, or true which means a default query variable with the name callback is being looked up.

因此,由于jQuery默认使用查询变量名 callback ,因此为 _jsonp定义了 true 应该这样做:

So as jQuery uses a query variable name of callback by default, defining true for _jsonp should do it:

$this->set(array(
    'member' => $members,
    '_serialize' => array('member'),
    '_jsonp' => true
));

如果没有名为 callback 的查询变量在请求URL中找到(即?callback =任何内容),您将收到常规的JSON响应。

In case no query variable named callback could be found in the request URL (ie ?callback=whatever), you'd receive a regular JSON response instead.

另请参见

这篇关于如何在cakephp 2.4中实现JsonP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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