开发者

AJAX vs PHP Directly into JS

I have a little bit of a conundrum. Basically I'm developing a WYSIWYG Editor plugin for jQuery specifically for my web application. One of the features will be inserting an inline image tooltip based on the images a user has uploaded. For example:

Hello there my name is [i="profile_pic.png"]A. Username[/i]

The part that I'm having an issue with is, when defining which images are available to a user, whether I should insert the PHP array directly into the Javascript like so:

var available_images = "<?=json_encode($User->Profile->images)?>";

or to go for an Ajax GET that returns an encoded array of the image sources? I think the inline php makes more sense since it removes the need for 开发者_如何学编程an unnecessary ajax call but I didn't think that inserting inline php into javascript is terribly good form?

Any suggestions?


There's nothing wrong with inserting data collected by PHP into JS, how else would JS get the data? The only reason you should consider the AJAX call would be, if users could upload new images while they are editing. This would mean the information needs to be updated, which would make the AJAX call more appealing than the static JSON on page load.


Unless the array changes in any way over the life time of the page, then I'd spit out the array exactly as you suggest in your code snippet. There isn't any real benefit to having an extra ajax call because the size of the array I'm guessing won't be so huge as to impact the initial page load time.

If you look around the Stack Overflow pages and do view-source, they do this sort of thing all the time.

If the amount of data is huge and maybe adds a seven or more seconds to the page load time then I'd consider an ajax call. At least the page is rendered and the user has something to look at, meanwhile you can have a throbber image with a status message saying loading or whatever.

I'd also say that I see a lot of unnecessary ajax goings on just for the sake of it. It's like premature optimisation, people adding complexity to solve a problem they don't have. Start off simple as you're doing, if you're having response time issues down the road with the said page, then consider what benefits ajax will bring to the table.


Do you always get the array of images, or only sometimes (e.g. in response to a user's action)? If the former, I'd say do it inline. Otherwise do it as AJAX. i.e. only do it by AJAX if it'll reduce your traffic etc. But if you have to always do it, I don't see any advantage. I don't see any problem with mixing inline php and javascript, other than it means you have to do your javascript inline too instead of in external .js files that can be cached (or at least the part where you populate your array).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜