Sunday, August 05, 2007

prototype javascript library ajax example


<div id="ajax_div">
use ajax to update it!
</div>
<br/>
<div id="ajax_failure">
if evalScript set false, sayHi is not defined!
</div>

<input type="button" name="button_ajax" value="ajax update div" id="button_ajax" />

<script type="text/javascript" charset="utf-8">
function doc(argument) {
document.write("<p>\n");
document.write(argument);
document.write("</p>\n");
}
var url = '/prototype/ajax_eval_script';
var options = {
method: 'get',
evalScripts: true,
parameters: 'id=1',
insertion: Insertion.Top
}

//new Ajax.Updater('ajax_div', url, options);
//new Ajax.Request(url, {onComplete: function (req) { alert(req.responseText); }});
var ajax = new Ajax.Request();
doc('ajax.transport type is ' + ajax.transport); //ajax.transport = Ajax.getTransport();
new Ajax.Updater({success: 'ajax_div', failure: 'ajax_failure'}, url, options);

ajax.setOptions(Object.extend(options, {onComplete: function(req) {
$('ajax_div').innerHTML = req + "<br/>\n" +
"req == ajax.transport is " + (req == ajax.transport) + "<br/>\n" +
"Server is " + req.getResponseHeader('Server') + "<br/>\n" +
"ajax request status is " + ajax.transport.status + "<br/>\n";
}
}));
$('button_ajax').onclick = function (event) { ajax.request('/prototype/ajax_eval_script'); };
</script>

/prototype/ajax_eval_script

<script language="javascript" type="text/javascript">
//function sayHi(){ // do nothing, function is not generated in runtime
//var sayHi = function(){ // not use the "var" keyword
sayHi = function(){
alert('Hi');
}
</script>

<input type="button" value="Click Me" onclick="sayHi()"/>
Note that in the previous example we did not use the var keyword to declare the variable. Doing so would have created a function object that would be local to the script block (at least in IE and FireFox). Without the var keyword the function object is scoped to the window, which is our intent.

No comments :