Ajax Quick Start, ajax
Ajax Quick Start
Ajax function: ajax is a technology that exchanges data with the server and updates some webpages without reloading the entire page. (implement data interaction between the browser and the server, implement the server without refreshing requests on the page, and improve the user experience)
Basic usage:
1. Create an ajax object:
New XMLHttpRequest () // used by a common browser. The IE browser has a special
2. Create an event function (processing the results returned by the server ):
Onreadystatechange
ReadyState ajax object status: 0: request not initialized 1: server connection established 2: request received 3: Request Processing in progress 4 request completed and response
Status response code: 200: 'OK' 404: Page Not found. 403: insufficient Permissions
ResponseText receives the data returned by the server
3. initialize ajax requests
Get --- xmlhttp. open ('get', 1.php? A = 1 & B = 2 & C-3 ', true );
Post --- xmlhttp. setRequestHeader ('content-type', 'application/x-www-form-urlencoded "):
Xmlhttp. open ('post', '1. php', true );
4. send an ajax request --- send ()
Server return
Echo common string
Common html files
Returns an xml string.
Index Array
Join Array
Notes
Same-origin policy-the current page must be the same as the server's Protocol address and port
Post sends an ajax request
--- SetRequestHeader ("content-type", 'application/x-www-from-urlencoded ");
--- Send parameter ("a = 100 & B = www ")
Use of firebug
Example:
<Script type = "text/javascript">
// 1. Create an ajax object
Var x = new XMLHttpRequest;
// 2. Trigger the event
X. onreadystatechange = function () {// on ready prepare state status changge
If (x. readyState = 4 & x. status = 200 ){
Console. log (x. responseText); // The returned result.
}
}
// 3. Initialization
X. open ('get', 'fuxi. php? Id = 100 ', true); // true asynchronous false is synchronous
// 4 send
X. send (); // send ajax
If the post method is used
Steps 3 and 4 change
X. open ('post', '3. php', true );
X. setRequestHeader ('content-type', 'application/x-www-form-urlencoded'); important
X. send ('a = 100 & B = 100 ');
Php PDO preprocessing
<? Php
$ Id = $ _ GET ['id'];
$ Pdo = new PDO ('mysql: host = localhost; dbname = pass; charset = utf8', 'root', '123 ');
// Prepare for preprocessing
$ Stmt = $ pdo-> prepare ('select * from phones where id =? ');
// Assign a value
$ Arr = [$ id];
// Execute
$ Stmt-> execute ($ arr );
// Obtain the result
$ Res = $ stmt-> fetch (PDO: FETCH_ASSOC );
// Var_dump ($ res );
$ Row = json_encode ($ res );
Echo $ row;