views:

20

answers:

2

Very common scenario using Ajax is to parse the response and create the user interface for end user. I am still new bee to the Ajax and UI words and i only see two choices to create the UI using Ajax (JSON/XML)response ,

  1. CreateElement() way and go on adding/removing elements dynamically
  2. Create big string and set innerHTML of some element

Now i have following queestion:

  1. Please let me know in case there is something else better choice to do so ?
  2. In case i would like to attach event to dynamically created elements what is the better way to do that ? I mean in many cases i end up doing something like

    <input onclick="somefunction()" />

Which i really feel bad doing and does cause issue and headaches.

Thanks

A: 

Try using existing Javascript UI frameworks like YUI, JQuery or even GWT. This will give you real good options and flexibility in case of XHR requests. Also it might be good for you to learn about event management in UI frameworks - once you get that idea, you can use it without these frameworks also here - see events in HTML in google

Koran
No no i have been using YUI but still creating UI dynamically from user response is kind of tricky that is my main concern. And my main intent is to know if in case there is better option to do that ... plainly at JavaScript/ DOM/HTML level....... . As i am sure libraries do it same way.
Anil Namde
A: 

I dont see anything wrong with those two approaches . However setting the innerHTML is better from performance point of view . In some cases creating the elements dynamically is the only option , you might want to take a look at documentFragment to avoid a lot of reflows ( again for performance reason ) .

ECMA specifies addEventListener to add listeners dynamically to your elements . You would also want to read about event bubbling .

NM