用JS或PHP构建div [关闭]

I've got an application that takes user form data and sends that to an external php file via ajax. The php file sends back rows from our database, which is then parsed in JS to generate some div strings and append them to the page. Is this bad practice? Should I be generating the divs in php and returning those instead?

This might end up being closed due to it being somewhat opinion based. However, in my experience it is best to generate UI things on the UI. So, creating your HTML in JS is a good thing. It keeps all of your view code out of the code that is fetching and returning your data. You could refer to it as the single responsibility principle (http://en.wikipedia.org/wiki/Single_responsibility_principle) in that PHP is responsible for getting the data, and JS is responsible for showing the data.

An example of where this ends up being important is "what if you need to use this data on another page?". If the display format is different, do you then start appending query parameters to tell PHP which way to build the divs.. or do you simply have the page that consumes the data build it how the page wants the data to be displayed? (Hint: you should chose the latter option)

No, this is not bad practice. Many javascript libraries allow you to generate HTML from data using templates. Also, just sending data reduces your application's bandwidth consumption. However, generating the div's server-side would (obviously) reduce client-side computation and code size. In other words, it depends on your situation.

It's not bad practice for PHP to render your view (I think that might partly be why it was created!), but within your PHP code it is bad practice to combine code that deals with database fetch operations with code that deals with your view. These should be nicely segregated.