with <Ajax on Rails>
Chapter 2 .Getting Our Feet Wet
S2.1. The Old-Fashioned Way
<p><a href="#" onclick="asyncAlert( )">Call async server-side</a></p>
<script type="text/javascript">
function asyncAlert( ) {
//Call server(IE-safe)
function getRequestObject( ) {
try { return new XMLHttpRequest( ) } catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch (e) {}
return false
}
var request = getRequestObject( );
request.open('get', '/chapter2/myresponse');
//we define a function that checks to see if readyState is 4 (which means the request is complete)
request.onreadystatechange = function( ) {
if(request.readyState==4) alert(request.responseText);
}
request.send( );
}
</script>
s2.2. javascript Libraries and Prototype
Prototype Way:
<script src="/javascripts/prototype.js" type="text/javascript">
</script>
<p><a href="#" onclick="prototypeAlert( );">Call with Prototype</a></p>
<script type="text/javascript">
function prototypeAlert( ) {
new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
alert(request.responseText);
}})
}
</script>
Update a element's innerHTML
<p><a href="#" onclick="updateElement( )">Update element </a></p>
<p id="response"></p>
<script type="text/javascript">
function updateElement( ) {
new Ajax.Request('/chapter2/myresponse', { onSuccess: function(request) {
$('response').update(request.responseText);
}})
}
</script>
================>
<p><a href="#" onclick="updater( )">Update with Ajax.Updater</a></p>
<p id="response2"></p>
<script type="text/javascript">
function updater( ) {
new Ajax.Updater('response2', '/chapter2/myresponse');
}
</script>
insert content:
<p><a href="#" onclick="appendToElement( )">Append to element</a></p>
<p id="response3"></p>
<script type="text/javascript">
function appendToElement( ) {
new Ajax.Updater('response3', '/chapter2/myresponse',
{ insertion:Insertion.Bottom });
}
</script>
//insertions: Before, Top, Bottom, and After.
===============>
<p><a href="#" onclick="new Ajax.Updater('response4',
'/chapter2/myresponse', { insertion:Insertion.Bottom });">
Append to element</a></p>
<p id="response4"></p>
转载请注明: 转自船长日志, 本文链接地址: http://www.cslog.cn/Content/learning_ajax_prototype/