开发者

CakePHP - Setting data retrieved from AJAX call to element

I'm making a new data entry through AJAX. It consists of the model data and some HABTM data as well. I return all this data as a json object from my controller and I would like to add a CakePHP view element containing this data to the current view, somewhat what twitter does when you post a tweet.

How can I manage to get the js开发者_运维技巧on object, append the element and set the data from the json object to said element? I have a good idea about how to append the element but the data setting I'm not clear about.


If I'm understanding your question correctly, you want to use CakePHP views to display the results of the JSON data?

If so, you can do it like this:

In your controller:

function my_ajax_action() {

   $data = // whatever method you use to fetch your data
   $this->set(compact('data'));
   $this->layout('ajax');

}

Create a view file: my_ajax_action.ctp which outputs the formatted $data array

Use ajax to fetch back the HTML not the JSON <- important bit and insert it into the DOM:

$.ajax({
    url: '/controller/my_ajax_action',
    success: function (result) {
        $('#myelement').html(result);
    }
});


Use $.getJSON to get the JSON, and then iterate and set the values on your page. Very straight forward..

Have a look here http://api.jquery.com/jQuery.getJSON/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜