开发者

Including Information in HTML for Javascript to Consume?

I'm am building a web app with app engine (java) and GWT, although I think my problem is moreso a general javascript question.

In my application, I want to include a side-menu which is generated from data in my database. This obviously needs to be done dynamically from a servlet开发者_C百科.

Currently, I am sending a blank menu container, then making an ajax call to get the information i need to populate the menu. I would rather just send the menu information along in the original request, so I do not need to waste time making a second request. I used this initial approach because it seemed simpler: I just wrote a gwt rpc service that grabbed the data i needed.

My question is, can I instruct a javascript library like gwt to look for its information in the current web page? Do I have to hide this information in my original HTML response, maybe in a hidden div or something?


If the data that you'd like to embed is restricted to menu items, why not directly generate lightweight HTML out of simple <ol> and <li> elements? You can still keep HTML out of your Java code by using a template engine. The menu markup could just be styled with CSS or if you need something fancier than mere <ol> and <li> elements, you can massage the DOM with JavaScript once the page loads (read: progressive enhancement).

If you're looking for a more generic solution, beyond the menu case, then you could embed a JSON block in your page, to be consumed when the page loads for the dynamic generation of your menu.

Or, you could look into using a microformat that is suitable for menu data.


You can include a script block in the original response defining the data and then use an onload event (or similar) to create the menu based on that data; that's very similar to what you're doing now, but without the extra trip to the server. I'm assuming there that the data to construct the menu is transformed in some way by JavaScript on the client; otherwise, just include the menu markup directly.


GWT has something called JSNI (Javascript Native Interface) that can interface with other non-GWT Javascript. So, you could in your HTML page container have a containing the generated menu items as a Javascript object. Then, in your GWT code, you have a JSNI call to fetch this data and put it in the right place in your UI/DOM with GWT methods.


I asked a similar question a few weeks ago about how to store data safely inside HTML tags. It also contains a few links to other questions. Here


There are in general 2 options:

  • Store the data in some xml tags somewhere in the html code and later get the information from there by traversing through the DOM. (you can hide them with css)
  • Store the data as JSON data in a script tag. (There en- and decoders for nearly every language)

    var data = { "foo" : "bar", "my_array":[] };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜