开发者

Organize 3 files: PHP, HTML, JS and Smarty

I have a php code page that pull data from a database. The data then should go into javascript, which is a separate .js file (and i need to use Jquery too). I want to separate my .js and my main html page too. How w开发者_开发知识库ould you do it, which one should be included in which? And if you also use Smarty, how will that change the structure? Thanks!


Whenever I'm generating Javascript data on the server side, I try to keep it entirely separate from the rest of the Javascript and HTML code. The cleanest way to do this is often to implement a basic API for your data: Create a PHP page that serves up pure JSON data from the database based on the URL and/or querystring, then use $.getJSON() to load it from the server. This approach avoids the cruft of generating Javascript with PHP, and allows for asynchronous loading of data, which may improve your UI.

If you don't want to deal with an asynchronous load, you can generate a file with just enough Javascript to define a variable:

echo 'var data = ' . json_encode($data) . ';';

and then refer to data in your subsequent Javascript.

Because this keeps the data wholly separate from your HTML and other Javascript files, it shouldn't have any influence at all on how you set up your templates.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜