开发者

AJAX - PHP Communication patterns

开发者 https://www.devze.com 2022-12-08 09:10 出处:网络
I\'m building a webapp in MySQL/PHP/Javascript. In PHP, I\'ve got all the classes from the domain od the problem which persist in the database.

I'm building a webapp in MySQL/PHP/Javascript.

In PHP, I've got all the classes from the domain od the problem which persist in the database. In Javascript, there is a cache with objects from the last queries.

When an object in Javascript is updated by the user, it has to update itself in server-side. Which would be the best w开发者_如何学运维ay to do this?

Should I create a class in PHP and Javascript for communication purposes? Should each object in Javascript send an AJAX query to a different php file depending on the class of the object it needs to update? Are there any patterns to follow to solve this?


Creating a separate PHP file for each class would certainly be more maintainable if this is a project of any size at all. It would also allow you to do things like have different server-level authentication based on the classes.

On the JavaScript side, you definitely want some sort of AJAX library, whether you throw it together yourself (I did one once in about 50 lines of JavaScript) or use one of the ones out there. You may need a helper function or two that knows how to serialize the data (XML, JSON, delimited, whatever).

You can write object oriented code in JavaScript, and if you're doing that already, it makes sense to add a write() or updateServer() method to call the AJAX library with the right parameters for consistency. If you're not writing OO code, it still may make sense to have separate functions, but only if there's more than one place you need to persist these objects from.


Most AJAX frameworks (jQuery etc) will send an 'HTTP_X_REQUESTED_WITH' header set to 'xmlhttprequest'. I like to use this to decide which view to use.

This means the same url can be used to retrieve JSON, XML, or HTML snippet via JavaScript or to return a full document if a standard GET / POST request is made.

This means your app will simply revert to normal requests should the user have JS disabled.


I think you should have a look into the RESTful API with PHP and JavaScript. You address your domain model objects as unique resources (e.g. /application/books/1). If you only want to implement CRUD functionality a generic Controller that updates the corresponding domain model (e.g using an ORM tool like Doctrine) should be sufficient.

If you really want to have the same model on the client side in JavaScript depends on your Application. I like the idea of just managing a single JavaScript object on the client side which will be loaded via REST and then populated to HTML Forms and send back e.g. as JSON (or as a simple form submit) to the server. If the client side model idea appeals to you, I recommend to have a look at JavaScript MVC which has a quite interesting model implementation.

0

精彩评论

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