Contoh Script AJAX Tradisional dengan CoffeeScript

18.55

main lepi
CoffeeScript:
validasi = (keyEvent) ->
    keyEvent ?= window.event
    input = keyEvent.target ?= keyEvent.srcElement
    if keyEvent.type is "keyup"
        targetDiv = document.getElementById "tempatTampilkan"
        targetDiv.innerHTML = "<div></div>"
        if input.value
            getData "data/validasiServerSide.php?qu=#{input.value}"
getData = (dataSource) ->
    objekXHR = false
    if window.XMLHttpRequest
        objekXHR = new XMLHttpRequest()
    else if window.ActiveXObject
        objekXHR = new ActiveXObject Microsoft.XMLHttp
    if objekXHR
        objekXHR.open "GET", dataSource
        objekXHR.onreadystatechange = ->
            if objekXHR.readystate is 4 and objekXHR.status is 200
                if objekXHR.responseText is "valid"
                    targetDiv = document.getElementById "tempatTampilkan"
                    targetDiv.innerHTML = "<div>Oke, Anda valid</div>"
                else
                    targetDiv = document.getElementById "tempatTampilkan"
                    targetDiv.innerHTML = "<div>Anda belum valid, coba lagi</div>"
        objekXHR.send null
Hasil (javaScript):
// Generated by CoffeeScript 1.9.3
(function() {
  var getData, validasi;

  validasi = function(keyEvent) {
    var input, targetDiv;
    if (keyEvent == null) {
      keyEvent = window.event;
    }
    input = keyEvent.target != null ? keyEvent.target : keyEvent.target = keyEvent.srcElement;
    if (keyEvent.type === "keyup") {
      targetDiv = document.getElementById("tempatTampilkan");
      targetDiv.innerHTML = "<div></div>";
      if (input.value) {
        return getData("data/validasiServerSide.php?qu=" + input.value);
      }
    }
  };

  getData = function(dataSource) {
    var objekXHR;
    objekXHR = false;
    if (window.XMLHttpRequest) {
      objekXHR = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      objekXHR = new ActiveXObject(Microsoft.XMLHttp);
    }
    if (objekXHR) {
      objekXHR.open("GET", dataSource);
      objekXHR.onreadystatechange = function() {
        var targetDiv;
        if (objekXHR.readystate === 4 && objekXHR.status === 200) {
          if (objekXHR.responseText === "valid") {
            targetDiv = document.getElementById("tempatTampilkan");
            return targetDiv.innerHTML = "<div>Oke, Anda valid</div>";
          } else {
            targetDiv = document.getElementById("tempatTampilkan");
            return targetDiv.innerHTML = "<div>Anda belum valid, coba lagi</div>";
          }
        }
      };
      return objekXHR.send(null);
    }
  };

}).call(this);

You Might Also Like

0 komentar

Back to top