Learning Ajax 1, Prototype

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>

此條目發表在 Ruby on Rails 分類目錄。將固定鏈接加入收藏夾。

發表評論