Ajax 2—-Make a request

  1. Get whatever data you need from the Web form.
  2. Build the URL to connect to.
  3. Open a connection to the server.
  4. Set up a function for the server to run when it's done.
  5. Send the request.

This is the basic step for every Ajax apllication.

function callServer() { // Get the city and state from the web form var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
// Only go on if there are values for both fields
if ((city == null) || (city == "")) return;
if ((state == null) || (state == "")) return;
// Build the URL to connect to
var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
// Open a connection to the server
xmlHttp.open("GET", url, true);

// Setup a function for the server to run when it's done
xmlHttp.onreadystatechange = updatePage;

// Send the request
xmlHttp.send(null);
}

function updatePage() {

if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText; document.getElementById("zipCode").value = response;
}
}

回复