开发者

Return data or html for internal cakephp api?

I am interested in learning which of two options is optimal for a cakephp api I am building. The api is internal, i.e. is only used for our web site to communicate with the backend. The api is called via jquery, and I see one of two options for the return format:

  1. Return raw json, and leave it up to the jquery front-end to parse it and build the html.
  2. Return 开发者_StackOverflow社区rendered html, so all the jquery needs to do is append the html to some container.

Both options have their pros and cons. I'll list them here and maybe you can extend this list.

Returning json:

  • Pros: the front-end has complete freedom to do as it may wish with the data. For example, if we need to store data in jquery about each link, then we can do that as we loop through the results and build the html.
  • Cons: I don't see a great solution as to where to store the html template for displaying the link. This is the reason I have thus far chosen Option 2. CakePHP has a very natural way of storing view templates and I exploited this feature. Embedding templates in the javascript is nasty!

Return rendered html:

  • Pros: Sort of the opposite of the above con; mainly, I can use CakePHP's built-in view-templating system to output the data.
  • Cons: Cumbersome to store jquery data on each link to use later (like to register an onClick event). Currently, in each link html I include some code like this:

    $('#this-link').data('someName', 'someData');

I am interested in hearing what others do to solve this issue. I've read that Twitter returns rendered html for performance reasons.

Thanks everyone.

Update: I believe my question is partially solved by using a framework like Backbone.js. Still, if (for performance reasons), we want to render the html on the backend, then we'd need to still pass data via the api. So an example json response might look like:

{
  id: 67,
  html: "<a href=\"profile.php?id=61\">Who is number 67?</a>"
}

Still not ideal, I don't think. I'd prefer for the javascript frontend to magically understand it is #67 :)


Usually, a web service API would have the option to specify the type of returned data in the request /type:json or /type:html. In the controller, do a switch(type): if html->render element, if json renderJSON

But since you don't make it public, you can get away it html-rendered result. If each link has its id, and you have to specify every link's data, then I don't see it's much more cumbersome. Remember, jquery has live('event',function(){}). You might find that useful.

Edit: $(theLink).data('id', linkId) why don't you just set the id of the link to that? and add class="need-to-click-blah" to all the link. So in jquery, you just need

$('.need-to-click-blah').live('click',function(){alert('link id: '+$(this).attr('id'));});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜