·
· With
·
· With
e.g
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
try
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support
return false;
}
}
}
}
</script>
Note:
· nternet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest.
· create the object with XMLHttp=new XMLHttpRequest(). This is for the Firefox, Opera, and Safari browsers.
If that fails, try xmlHttp=new ActiveXObject("Msxml2.XMLHTTP") which is for Internet Explorer 6.0+, if that also fails, try xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") which is for Internet Explorer 5.5+
The onreadystatechange Property
After a request to the server, we need a function that can receive the data that is returned by the server.
The onreadystatechange property stores the function that will process the response from a server. The following code defines an empty function and sets the onreadystatechange property at the same time:
xmlHttp.onreadystatechange=function() {
// We are going to write some code here
}
The readyState Property
The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed.
Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete
We are going to add an If statement to the onreadystatechange function to test if our response is complete (this means that we can get our data):
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
// Get the data from the server's response
}
}
The responseText Property
The data sent back from the server can be retrieved with the responseText property.
In our code, we will set the value of our "time" input field equal to responseText:
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
document.myForm.time.value=xmlHttp.responseText;
}
}
To send off a request to the server, we use the open() method and the send() method.
The open() method takes three arguments. The first argument defines which method to use when sending the request (GET or POST). The second argument specifies the URL of the server-side script. The third argument specifies that the request should be handled asynchronously. The send() method sends the request off to the server. If we assume that the HTML and ASP file are in the same directory, the code would be:
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
Now we must decide when the
<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>
Our updated AJAX-ready "testAjax.htm" file now looks like this:
<html>
<body>
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support
return false;
}
}
}
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
document.myForm.time.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","time.asp",true);
xmlHttp.send(null);
}
</script>
<form name="myForm">
Name: <input type="text"
onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>
Now we are going to create the script that displays the current server time.
The responseText property (explained in the previous chapter) will store the data returned from the server. Here we want to send back the current time. The code in "time.asp" looks like this:
<%
response.expires=-1
response.write(time)
%>
Note: The Expires property sets how long (in minutes) a page will be cached on a browser before it expires. If a user returns to the same page before it expires, the cached version is displayed. Response.Expires=-1 indicates that the page will never be cached.
Example Explained - The HTML Form
The form above has the following HTML code:
<form>
First Name:
<input type="text" id="txt1"
onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
As you can see it is just a simple HTML form with an input field called "txt1".
An event attribute for the input field defines a function to be triggered by the onkeyup event.
The paragraph below the form contains a span called "txtHint". The span is used as a placeholder for data retrieved from the web server.
When the user inputs data, a function called "showHint()" is executed. The execution of the function is triggered by the "onkeyup" event. In other words: Each time the user moves his finger away from a keyboard key inside the input field, the function showHint is called.
Example Explained - The showHint() Function
The showHint() function is a very simple JavaScript function placed in the <head> section of the HTML page.
The function contains the following code:
function showHint(str) {
if (str.length==0) {
document.getElementById("txtHint").innerHTML="";
return;
}
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null) {
alert ("Your browser does not support
return;
}
var url="gethint.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
The function executes every time a character is entered in the input field.
If there is some input in the text field (str.length > 0) the function executes the following:
* Defines the url (filename) to send to the server
* Adds a parameter (q) to the url with the content of the input field
* Adds a random number to prevent the server from using a cached file
* Creates an XMLHTTP object, and tells the object to execute a function called stateChanged when a change is triggered
* Opens the XMLHTTP object with the given url.
* Sends an HTTP request to the server
If the input field is empty, the function simply clears the content of the txtHint placeholder.
Example Explained - The GetXmlHttpObject() Function
The example above calls a function called GetXmlHttpObject().
The purpose of the function is to solve the problem of creating different XMLHTTP objects for different browsers.
The function is listed below:
function GetXmlHttpObject(){
var xmlHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Example Explained - The stateChanged() Function
The stateChanged() function contains the following code:
function stateChanged(){
if (xmlHttp.readyState==4) {
document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
}
}
The stateChanged() function executes every time the state of the XMLHTTP object changes.
While responseText returns the HTTP response as a string, responseXML returns the response as XML.
The ResponseXML property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.
The example above contains an HTML form, several <span> elements to hold the returned data, and a link to a JavaScript:
<html>
<head>
<script src="selectcustomer_xml.js"></script>
</head>
<body>
<form action="">
Select a Customer:
<select name="customers" onchange="showCustomer(this.value)">
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<b><span id="companyname"></span></b><br />
<span id="contactname"></span><br />
<span id="address"></span>
<span id="city"></span><br/>
<span id="country"></span>
</body></html>
The example above contains an HTML form with a drop down box called "customers".
When the user selects a customer in the dropdown box, a function called "showCustomer()" is executed. The execution of the function is triggered by the "onchange" event. In other words: Each time the user change the value in the drop down box, the function showCustomer() is called.
The
This is the JavaScript code stored in the file "selectcustomer_xml.js":
var xmlHttp
function showCustomer(str) {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("Your browser does not support
return;
}
var url="getcustomer_xml.asp";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function stateChanged(){
if (xmlHttp.readyState==4) {
var xmlDoc=xmlHttp.responseXML.documentElement;
document.getElementById("companyname").innerHTML=
xmlDoc.getElementsByTagName("compname")[0].childNodes[0].nodeValue;
document.getElementById("contactname").innerHTML=
xmlDoc.getElementsByTagName("contname")[0].childNodes[0].nodeValue;
document.getElementById("address").innerHTML=
xmlDoc.getElementsByTagName("address")[0].childNodes[0].nodeValue;
document.getElementById("city").innerHTML=
xmlDoc.getElementsByTagName("city")[0].childNodes[0].nodeValue;
document.getElementById("country").innerHTML=
xmlDoc.getElementsByTagName("country")[0].childNodes[0].nodeValue;
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try { // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) { // Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
The showCustomer() and GetXmlHttpObject() functions above are the same as in previous chapters. The stateChanged() function is also used earlier in this tutorial, however; this time we return the result as an XML document (with responseXML) and uses the DOM to extract the values we want to be displayed.
The
The server page called by the JavaScript, is a simple ASP file called "getcustomer_xml.asp".
The page is written in VBScript for an Internet Information Server (IIS). It could easily be rewritten in PHP, or some other server language. Look at a corresponding example in PHP.
The code runs an SQL query against a database and returns the result as an XML document:
<%
response.expires=-1
response.contenttype="text/xml"
sql="SELECT * FROM CUSTOMERS "
sql=sql & " WHERE CUSTOMERID='" & request.querystring("q") & "'"
on error resume next
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/northwind.mdb"))
set rs=Server.CreateObject("ADODB.recordset")
rs.Open sql, conn
if err <> 0 then
response.write(err.description)
set rs=nothing
set conn=nothing
else
response.write("<?xml version='1.0' encoding='ISO-8859-1'?>")
response.write("<company>")
response.write("<compname>" &rs.fields("companyname")& "</compname>")
response.write("<contname>" &rs.fields("contactname")& "</contname>")
response.write("<address>" &rs.fields("address")& "</address>")
response.write("<city>" &rs.fields("city")& "</city>")
response.write("<country>" &rs.fields("country")& "</country>")
response.write("</company>")
end if
on error goto 0
%>
Notice the second line in the ASP code above: response.contenttype="text/xml". The ContentType property sets the HTTP content type for the response object. The default value for this property is "text/html". This time we want the content type to be XML.
No comments:
Post a Comment