Reputation: 5176
What's the best way to add dynamic content to a web page after a successfull xml http request. To break down a more concrete example:
Sites like Facebook or last.fm (when you post a shout, ie) send the processed markup in a direct object back to the javascript, instead of just the processed data. An example of this written in jQuery would be
$('#activeField').html(callback.data);
Another way to do this is to create the dom elements on the fly with javascript. I find this too clumsy as there's no easy (?) and simple way of doing this today. At the same time, sending the processed markup directly from the server violates our application's design principles (MVC), as having markup in a front controller is not preferred.
What's the "best practices" way of doing this? Thanks!
Upvotes: 1
Views: 237
Reputation: 57815
At the same time, sending the processed markup directly from the server vioalates our application's design principles (MVC), as having markup in a front controller is not preferred.
I may be missiing the point, but could you not send markup from the server by rendering it within a view as you would normally, rather than having to have markup in your controller? Assuming your View mechanism has the ability to return rendered HTML rather than outputting it immediately, you could retrieve this and then add it to an array before calling json_encode()
and outputting it. You could potentially then use the same view code to render this piece of HTML regardless of whether it is being fetched as part of a full page or via an AJAX call.
Upvotes: 2
Reputation: 75824
I think this question pushes too far on subjective perhaps, but personally I believe the best plan is for the request to return JSON which describes both the content and the mechanism (by which I mean javascript method) for serialising that to HTML if multiple possibilities exist. This saves on bandwidth and (as you've pointed out) preserves your separation of concerns. The last thing I want really is for my front-end guys to have to deal with arbitrary mark-up from the server-side guys. Abstraction is good.
I don't really get why you feel JS generated mark-up is clumsy or difficult. A handful of JS methods which parse and generate standard JSON structures seems lightweight and trivial to me, though I must admit I've always rolled my own here. Almost certainly there's a framework for this out there (anyone?). If not, well I've got this great business idea...
Upvotes: 1