how to implement JsonP in cakephp 2.4

2019-04-13 09:46发布

问题:

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.

Do I need an extra piece of code to send the callbck back?

My Controller

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 code

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

回答1:

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

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.

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

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.

See also

  • Cookbook > Views > JSON and XML views > JSONP response


回答2:

If that just don't work, try to change the value of $jsonpParam from "callback" to "jsoncallback" (in lib/Cake/View/JsonView.php). I had to do that for make it work, thats because the name of the variable in the jsonp request, is jsoncallback, this one contains the string of the callback.