![]() | ||||||||||||||||||||||
|
|
![]() XMLHttpRequest (AJAX) - sending and processing of answers of http-searches with help JavaScript. In interactivity - static html sites are the past. Dynamic with use CGI (or modules of the server, for example Apache) and databases when the server at sending the form forms page and shows than her after updating - hardly is more modern, but nevertheless in many areas where interactivity is required practically sopostovimaja with desktopnymi applications - as die away. On change there come the interactive functional programs to the full cooperating with the user; the information received from the server practically instantly is displayed on the screen without perezagruzke pages. Speech I to a kind about AJAX'e, that in decoding " asynchronous JavaScript and XML " (the term has entered Dzhess Garrett). And if in more detail, - " asynchronous JavaScript + CSS + DOM + XMLHttpRequest ". Methods of object XMLHttpRequest All nizheizlozhannye methods and properties - the general{common} for Internet Explorer 5, Mozilla, Netscape 7, and accordingly to use them it is possible safely. abort () Breaks off the current search getAllResponseHeaders () Returns a full set of headings of the answer (names and values) as a line getResponseHeader (<headerLabel>) Returns line value of heading which name is specified in parameter. open (<method>, <URL> [, <asyncFlag> [, <userName> [, <password>]]]) Assignment of parameters (a method, URL, and others) to the current search. send (<content>) Sends search setRequestHeader (<label>, <value>) Installation in sent search of heading <label> with value <value> Properties of object XMLHttpRequest onreadystatechange The event arising at change of the status of object readyState Values of the status (integer), can accept the following values: 0 = neinicializirovan (uninitialized); 1 = " there is a loading " (loading); 2 = "is loaded" (loaded); 3 = "is interactive" (interactive) 4 = "is executed" (complete) responseText Line with the data returned by the server responseXML The DOM-compatible object - document with the data returned by the server status Standard HTTP a code of the status, for example 404 (for " Not Found ") or 200 (for "OK") statusText The text message of the status Here all necessary properties and methods of this object which will help us to solve ours task. We shall describe sequence of our actions: Algorithm: 1. Creation of a copy of object XMLHttpRequest. 2. The announcement obrabotchika events onreadystatechange our copy. 3. Opening connection with the instruction{indication} such as search, URL and other parameters. 4. Posyl search. The algorithm is plain, but, taking into account some nuances (and taking into account, that we study:)), certainly, we shall consider it more in detail: So, item{point} the first - creation of a copy of object. Feature of maintenance krossbrauzernosti here emerges. The design of creation of object is various: in IE 5 + she is realized through ActiveXObject, and in other browsers (Mozilla, Netscape and Safari) - as the built - in object such as XMLHttpRequest. For Internet Explorer: var request = new ActiveXObject (" Microsoft. XMLHTTP "); For all others: var request = new XMLHttpRequest (); So that to provide krossbrauzernost`, it is necessary to check only presence of objects window. XMLHttpRequest and window. ActiveXObject and to apply a corresponding call of creation of a copy. Further under the plan - creation obrabotchika events and opening of connection. It is rather simple: request.onreadystatechange = processRequestChange; request.open ("GET", url, false); Here we use method GET though it is possible and POST; in a general view it vygljadet so: request.open (<"GET" | "POST" |...>, <url>, <asyncFlag>);. The function being obrabotchikom of event onreadystatechange (in our case it is function - processRequestChange ()), we should define{determine}. Well and last item{point} - posyl search - a method send () (for the version without ActiveX as parameter it is necessary to pass null). // For IE request.send (); // For the others request.send (null); After start of a method send () starts to work above-stated obrabotchik events onreadystatechange. Actually, this obrabotchik - the basic part of the program. In him all possible{probable} codes of a status of search are usually intercepted and corresponding actions are caused, and also possible{probable} mistakes are intercepted. Proceeding from all aforesaid, JavaScript the code will be approximately sleduhhim: var request; / ** * Load XMLDoc function * Here as parameter url by a call we should specify * A backend-script which, actually, also will obtain the data from the server */ function doLoad (url) { if (window. XMLHttpRequest) { request = new XMLHttpRequest (); request.onreadystatechange = processRequestChange; request.open ("GET", url, true); request.send (null); } else if (window. ActiveXObject) { request = new ActiveXObject (" Microsoft. XMLHTTP "); if (request) { request.onreadystatechange = processRequestChange; request.open ("GET", url, true); request.send (); } } } / ** * Get request state text function */ function getRequestStateText (code) { switch (code) { case 0: return "Uninitialized."; break; case 1: return " Loading... "; break; case 2: return "Loaded."; break; case 3: return " Interactive... "; break; case 4: return "Complete."; break; } } / ** * Event on request change * Actually, obrabotchik events onreadystatechange. * Here we, depending on a status of search, * We shall hide / to show layers " Loading of the data ", * A field of the data, etc. */ function processRequestChange () { document.getElementById ("resultdiv") .style.display = 'none'; document.getElementById ("state") .value = getRequestStateText (request.readyState); abortRequest = window.setTimeout (" request.abort (); ", 10000); // If it is executed if (request.readyState == 4) { clearTimeout (abortRequest); document.getElementById ("statuscode") .value = request.status; document.getElementById ("statustext") .value = request.statusText; // If it is successful if (request.status == 200) { document.getElementById ("resultdiv") .style.display = 'block'; document.getElementById ("responseHTML") .innerHTML = request.responseText; } else { alert (" it was not possible to receive dannye:n " + request.statusText); } document.getElementById ("loading") .style.display = 'none'; } // Differently, if there is a loading or in process - show a layer " the data Are loaded " else if (request.readyState == 3 || request.readyState == 1) { document.getElementById ("loading") .style.display = 'block'; } } Now HTML-forms of our example: <input type = "text" id = "search" value = " Enter the first letters nika " onFocus = " this.value = "; document.getElementById ('resultdiv') .style.display ='none '; " /> <input type = "button" value = "Search" onClick = " doLoad (' ajaxsearch.php? search = ' + document.getElementById ('search') .value); " /> <br/> <br/> The additional information on performance of search: <br/> <br/> <table> <tr> <td> the Status of search: </td> <td> <input type = "text" id = "state" disabled = "true"/> </td> </tr> <tr> <td> the Code of the status: </td> <td> <input type = "text" id = "statuscode" disabled = "true"/> <input type = "text" id = "statustext" disabled = "true"/> </td> </tr> </table> Turn vnimenie on a fragment selected zelennym with color - event onClick buttons " Searches ". We cause funkicju doLoad(... as which parameter we pass the address of the backend-script which is carrying out search in base of the registered user. About a backend-scratch hardly later, we have defined{determined} a name of it as ajaxsearch.php. Also in GET-parameter we pass a script a variable search, with the value taken from a field of input for nika. And, as it has been said above, we shall declare additional HTML-elements (in our case are invisible layers) for display of the received contents and a window of loading with an opportunity of a cancellation: <div id = "resultdiv" style = " display: none; "> Rezul`aty search: <span id = "responseHTML"> </span> </div> <div id = "loading" style = " position: absolute; top: 450px; left: 550px; display: none; width: 125px; height: 40px; font-family: Verdana; font-size: 11pt; border: 1px solid *BBBBBB; background: *EEEEEE; padding: 5px 5px 5px 5px; " > Loading data... <div id = "canselloading" style = " background: red; border: 1px solid *000000; color: *FFFFFF; padding: 2px 2px 2px 2px; cursor: pointer; " onClick = " request.abort (); document.getElementById ('loading') .style.display = 'none'; return false; " > Cansel </div> </div> Well, with frontend'om have understood, we pass to backend'T - a script ajaxsearch.php. And again we collide{face} with small nuances: that the PHP-script correctly worked with XMLHttpRequest, he (script) should send a number{line} of headings. Namely: a content type and his coding (it is especially important if you work with cyrillics), and also parameters keshirovanija - any keshirovanie should be switched - off (well it and is understandable - it is necessary to have I skin the information). To send these headings it is possible, approximately, so: header (" Content-type: text/html; charset=windows-1251 "); header (" Cache-Control: no-store, no-cache, must-revalidate "); header (" Cache-Control: post-check=0, pre-check=0 ", false); And more one feature: if you will be deduces the data in a format text/plane (in our case - text/html, therefore us it not kasnetsja, but nevertheless - to know), remember, that specsimvoly such as n, t, r, etc., are processed by default only in lines with double inverted commas: // I.e. it is correct so print " MessagenFrom AJAX "; // Instead of so! print ' MessagenFrom AJAX '; Well and now rather banal PHP-script of data acquisition from base (and banal because it is supposed, that you already have skills of job with databases in PHP). A kind of a script the following (in najdenykh nikakh we highlight letters of search red color and we deduce{remove} all this as the table): <? php
/ ** * Posyl headings */
header (" Content-type: text/plain; charset=windows-1251 "); header (" Cache-Control: no-store, no-cache, must-revalidate "); header (" Cache-Control: post-check=0, pre-check=0 ", false);
/ ** * A host, a login and the password of a database * (to you, naturally, it is necessary to replace with the values) */
$dbhost = "localhost"; $dblogin = "root"; $dbpassword = "root";
/ ** * Konnektimsja to base, we carry out * Search, we receive result */
@mysql_connect ($dbhost, $dblogin, $dbpassword) or die (" Unable to connect to database.. "); @mysql_select_db ("MYDATABASE") or die (" Unable to select database "); $sql = " SELECT * FROM users WHERE nick LIKE ' % ". $ _GET ["search"] ". % ' ORDER BY nick "; $result = mysql_query ($sql);
print " It is found on search: " .mysql_num_rows ($result);
/ ** * If there are numbers{lines}, deduce{remove} the table */
if (mysql_num_rows ($result)> 0) { print "<table>"; print "<tr>"; print " <td> NickName </td> "; print " <td> RealName </td> "; print " <td> E-mail </td> "; print "</tr>";
$get = $ _GET ["search"];
while ($row = mysql_fetch_array ($result)) { print "<tr>"; print "<td>"; print ($row ["unick"]? preg_replace (" / ($get)/i ", " <font color ='red '> \1 </font> ", $row ["unick"]): " *nbsp; "); print "</td>"; print " <td> ($row ["urealname"]? $row ["urealname"]: " *nbsp; ") </td> "; print " <td> $row ["umail"] </td> "; print "</tr>"; } print "</table>"; }
?> |
|||||||||||||||||||||