Bite My Code

the code with no tag

Simple Ajax based on Prototype Framework

without comments

Prototype is one of the most commonly used ajax framework in web2.0. Here is a very simple example to make a ajax page loading in the HTML.

First, you need to have the prototype framework, you can download here, or you can use the included one in the example zip file.

I wrapped the ajax page loading function in a javascript function, so we can reuse this function more easily, here is the javascript code:


function loadPage(pageURL, displayID, queryStr) {
var url = encodeURIComponent(pageURL);
var params = '';
if (queryStr != undefined)
params = queryStr;

new Ajax.Request(url, {
method: 'get', parameters: params,
onSuccess: function(transport) {

if(transport.responseText.length > 0){
document.getElementById(displayID).innerHTML=transport.responseText;
}}});
}

You need to pass 3 parameters for this function:

  1. pageURL - the page url which you want to load, without the HTML and BODY tag
  2. displayID - the div id which the result will be displayed
  3. queryStr - name and value pair for dynamic page, which is optional

And you need to define the display div in the HTML as follow:

<div id="display_body">
</div><br />

Now, you can simply use this javascript to load a page by ajax:

<a href="javascript:loadPage('hello-world.html', 'display_body')">Load Hello World Page</a>

And here is the example source in zip format:
Download Here

Feel free to give any comments for us, thanks.

  • Digg
  • del.icio.us
  • Facebook
  • Google
  • Live
  • Reddit
  • YahooMyWeb

Written by alvin

August 7th, 2008 at 12:24 pm

Posted in Web Development

Tagged with , , ,

Leave a Reply