问题
I just finished an intro to web dev course in my CS program and came away wondering something simple. When should you use JavaScript (client-side) instead of server-side (we used PHP but anything applies) code? Vice-versa as well.
回答1:
There is no recipe for deciding that. A few notes:
- security and validation should always be present at the server side (sometimes duplicated in the client).
- the client-side should contain only UI-logic. No business logic.
- logically, everything that accesses a database should be on the server.
Of course, if your application is a RIA (rich internet app), then you can have logic on the client. So it all depends.
回答2:
Javascript should be only used to manipulate the UI of the page. You can also do certain validations using it, however, there must be corresponding validation on the server-side. For doing any data manipulation, applying business logic, etc you should always use server side code.
Here are some cases where you will use client-side code:
- Changing the look (UI) of the page e.g. dynamically show/hide some elements
- Validate user inputs (this should also be done on server side)
Cases where to use server-side code:
- Validation of user inputs (should always be done on server side irrespective of whether done on client side or not.)
- User authentication
- Business logic (deciding what to show to which users, calculations)
- Database access
回答3:
Imho i would say, use server-side if you can. All client-side code can be manipulated. Or maybe will not run cause the browser dont support it.
来源:https://stackoverflow.com/questions/8586425/when-to-use-client-side-or-server-side