Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax: Building HTML vs injecting HTML

Trying to comply with StackOverflow's suggestion of asking a question, not creating a discussion, let us consider these two methods that use the HTTPAsyncRquest to update a web page without refreshing it:

1) Data returned by AsyncRequest is parsed/interpreted in order to build the resulting HTML that updates the page e.g. JSON::parseAndExecute(returnedData); // Just an example

2) Data returned by AsyncRequest is raw jScript which is executed and updates the page. e.g. plain old: eval(returnedData); // we KNOW returnedData is not malicious code

To rule out academic/preferences issues, let's assume we use the exact same framework to program both server and client, with the only difference being that there is an option/flag to make it spit out a JSON or raw jscript.

In that scenario, are there technical reasons for which one should prefer either?

I ask this because raw JSCRIPT should be, in most cases, faster and more flexible, but most frameworks I've found do not return JSCRIPT, but instead data that is in turn interpreted by JSCRIPT.

(Just to clarify: I'm asking is it smaller? faster? are there security risks? compatiblity risks?)

First post at stackoverflow, ye!

like image 237
Migs Avatar asked Nov 05 '22 21:11

Migs


2 Answers

Your second solution would generally be faster, easier to implement and use less bandwidth. And if you control both the server-side and the client-side in e.g. an Ajax Framework, then security is no problem. So your only problem is that you end up with an (evil) eval. Which you must have ANYWAY since except for on IE8 there are no ways to "parse" JSON without having at least one eval in your code.

We're (Ra-Ajax) using a combination of JSON and HTML (innerHTML for all practical concerns) for our Ajax Engine. We're using JSON to change properties an attributes on our widgets, while we're using innerHTML on initial rendering (or complete updates) on widgets.

like image 100
Thomas Hansen Avatar answered Nov 11 '22 03:11

Thomas Hansen


@Thomas Hansen:

Faster and easier to implement, maybe. But I don't see why it'd use less bandwidth. Javascript code loaded with pages get cached so the parsing and widget-building code will get downloaded only once, the dynamic stuff is just pure JSON.

You could also prefer the first option (JSON) because you're somehow transforming/filtering data in response to other GUI callbacks, and don't want to rely on the server for that.

like image 29
Camilo Díaz Repka Avatar answered Nov 11 '22 04:11

Camilo Díaz Repka