วันศุกร์ที่ 12 เมษายน พ.ศ. 2556

Ajax in jQuery


General Flow

1. create XMLHttpRequest object
2. configure XMLHttpRequest object with data to send to server
3. attach callback function to read server response
4. connect to server with send() function
5. interpret response from server
6. extract data from XMLHttpRequest object

load(url, parameters, callback) function

  $("div").load("http://127.0.0.1/message.txt"); << load data from message.txt to <div> element
NOTE:
- use GET method by default
- use POST if pass parameter to server
- load data to element

load() function with callback (executed after data loaded)

  $("div").load("http://127.0.0.1/message.txt", callback); << load data from message.txt to <div> element
  ...
  function callback() {
    $("#targetDiv").text("Got the data.");
  }

load() function with parameter

  $("div").load("poster.php", {data: 1}); << parameter name = data, value = 1

pass form data to server (use serializeArray() function)

  <form id="targetForm">
    ...
  </form>
  ...
  $("div").load("poster.php", $("#targetForm").serializeArray());

$.get(), $.post() << explicitly use GET/POST method
  $.post("poster.php", {data: 1}, function(data){ << parameter data = data from server
    $("div").text(data);
  });
NOTE:
- explicitly use GET/POST method
- get downloaded data directly (without loading to element)
- when pass parameters, GET append param value to URL, POST pass param values in HTTP header

$.ajax() function

  $.ajax({
    type: "GET",          << GET/POST method
    url: "getter.php",    << URL to retrieve content
    data: {data: 1},      << data passed to server
    success: callback,    << callback function if success
    timeout: 10,          << timeout in msec
    error: error          << callback function if error
  });

  function callback(data, status) { << data = data returned from server
      $("div").text(data);
  }

  function err(xhr, reason, ex) {   << xhr = XMLHttpRequest object; reason = reason text; ex = Exception object
      $("div").text(reason);
  }

use Ajax to handle XML

  $.ajax({
    type: "GET",
    url: "sandwiches.xml",  << source data
    dataType: "xml",        << data type = xml
    success: callback
  });
  ...
  function callback(data, status) {
    var sandwiches = data.getElementsByTagName("sandwich"); << get data from XML
    listSandwiches(sandwiches);
  }

  function listSandwiches (sandwiches) {
    var loopIndex;
    var selectControl = document.getElementById('sandwichList');

    for (loopIndex = 0; loopIndex < sandwiches.length; loopIndex++) {
        selectControl.options[loopIndex] = new Option(sandwiches[loopIndex].firstChild.data);
    }
  }

Ajax global events

  $("#starting").bind("ajaxStart", function(){ << global event AjaxStart
   $(this).show();
  });
  ...
  <div id="starting">Starting...</div>
NOTE: there are AjaxStart, AjaxSend, AjaxSuccess, AjaxError, AjaxComplete, AjaxStop

ไม่มีความคิดเห็น:

แสดงความคิดเห็น