What Is Async Loading?
The simplest way to put it is: inserting data from another page into the current page using functions like append() or html(). In plain JS, this means inserting responseXML or responseText into the page.
The other page can be static, dynamic, or even JSON/XML data.
The principle is basically the same — for pages, it’s convenient, just grab the code we want and insert it; for JSON and XML, we need to parse and place the appropriate data in the right spot.
Dynamic pages can also be parsed as long as they generate JSON or XML formatted pages.
The jQuery API usage:
$.post(url, [data], [callback], [type])
//$get
$.get(url, [data], [callback], [type])
//$ajax
$.ajax([options])
DEMO:http://www.dbpoo.com/demo/ajax/test1/
First, let’s get familiar with $.ajax interacting with PHP.
The example below demonstrates how to expand post content when clicking a post title in WordPress.
The principle is: by inspecting the code post-123, we know that the 123 after it is the ID value from the post table in the database, so finding the content by ID is very straightforward.
JavaScript Code:
$('.post').click(function(){
var arr= new Array();
var postIDdiv = $(this).attr("id");
var arr = postIDdiv.split('-');
postID = arr[1];
if($('#'+postIDdiv+' .content').html() == ''){changeData(postID);}
})
function changeData(postID){
$.ajax({
type:'GET'
,url:'file.php'
,data:{id:postID}
//The url and data above are equivalent to: url:'file.php?id='+postID+''
,contentType:'text/html;charset=utf-8'//encoding format
,beforeSend:function(data){
$('#post-'+postID+' .info').html('loading…');
}//before request is sent
,success:function(data){
$('#post-'+postID+' .content').html(data);
//alert(data);
}//after request succeeds
,error:function(data){
$('#post-'+postID+' .info').html('failed to load data.')
}//request error
,complete:function(data){
$('#post-'+postID+' .info').html('');
}/request complete
});
}
})
PHP Code:
//
$db = new mysqli('localhost','root','1234','vivi');
//$db->query("SET NAMES utf8");
mysqli_query($db,"SET NAMES utf8");
if(!$db){
echo 'Database connection failed!';
}else{
if(isset($_GET['id'])){
$id = $db->real_escape_string($_GET['id']);
$query = $db->query("select * from posts where id = '$id'");
//echo $result->post_content;
if($query) {
//echo 'ok';
while ($result = $query->fetch_object()) {
//echo $db->character_set_name();
echo $result->post_content;
}
} else {
echo 'Error: no data.';
}
}else{
echo 'no';
}
}
$db->close();
Detailed Parameter Reference:
1) $post
data (Map) : (optional) Data to send to the server, expressed as Key/Value pairs.
callback (Function) : (optional) Callback function on successful load (only called when the Response status is success).
type (String) : (optional) The official description is: Type of data to be sent. It actually refers to the client request type (JSON, XML, etc.)
2) $get
data (Map) : (optional) Data to send to the server, expressed as Key/Value pairs, appended to the request URL as a QueryString.
callback (Function) : (optional) Callback function on successful load (only called when the Response status is success).
3) $ajax
| Parameter | Type | Description |
| url | String | (Default: current page URL) The URL to send the request to. |
| type | String | (Default: “GET”) The request method (“POST” or “GET”), defaults to “GET”. Note: Other HTTP methods such as PUT and DELETE can also be used, but only some browsers support them. |
| timeout | Number | Sets the request timeout (in milliseconds). This setting overrides the global setting. |
| async | Boolean | (Default: true) By default, all requests are sent asynchronously. Set this option to false to send a synchronous request. Note that synchronous requests will lock the browser, and the user must wait for the request to complete before performing any other operations. |
| beforeSend | Function | A function to modify the XMLHttpRequest object before sending the request, such as adding custom HTTP headers. The XMLHttpRequest object is the only parameter.
function (XMLHttpRequest) {
this; // the options for this ajax request } |
| cache | Boolean | (Default: true) New in jQuery 1.2. Set to false to prevent loading request information from the browser cache. |
| complete | Function | A callback function called after the request completes (whether the request succeeds or fails). Parameters: XMLHttpRequest object, success status string.
function (XMLHttpRequest, textStatus) {
this; // the options for this ajax request } |
| contentType | String | (Default: “application/x-www-form-urlencoded”) The content encoding type when sending information to the server. The default value suits most applications. |
| data | Object, String |
Data to send to the server. It will be automatically converted to a query string format. In GET requests, it will be appended to the URL. See the processData option to disable this automatic conversion. Must be in Key/Value format. If an array is used, jQuery will automatically use the same name for different values. For example, {foo:[“bar1”, “bar2”]} will be converted to ‘&foo=bar1&foo=bar2’. |
| dataType | String |
The type of data expected from the server. If not specified, jQuery will automatically determine it based on the HTTP package MIME information and return responseXML or responseText, passing it as a parameter to the callback function. Available values: “xml”: Returns an XML document that can be processed with jQuery. “html”: Returns plain text HTML; includes script elements. “script”: Returns plain text JavaScript code. Results are not automatically cached. “json”: Returns JSON data. “jsonp”: JSONP format. When using the JSONP format to call a function, e.g. “myurl?callback=?”, jQuery will automatically replace ? with the correct function name to execute the callback. |
| error | Function | (Default: auto-detected (xml or html)) This method is called when the request fails. It has three parameters: the XMLHttpRequest object, error message, and (optionally) the captured error object.
function (XMLHttpRequest, textStatus, errorThrown) {
// Typically, only one of textStatus and errorThrown has a value this; // the options for this ajax request } |
| global | Boolean | (Default: true) Whether to trigger global AJAX events. Set to false to prevent global AJAX events such as ajaxStart or ajaxStop from being triggered. Can be used to control different Ajax events. |
| ifModified | Boolean | (Default: false) Only fetch new data when the server data has changed. Determined using the HTTP package Last-Modified header. |
| processData | Boolean | (Default: true) By default, data sent will be converted to an object (technically not a string) to match the default content type “application/x-www-form-urlencoded”. Set to false if you want to send DOM tree information or other data that should not be converted. |
| success | Function | A callback function called after a successful request. This method has two parameters: the data returned by the server and the return status.
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc… this; // the options for this ajax request } |
Additional Notes:
1. $.load( url, [data], [callback] ): Load remote HTML file content and insert it into the DOM.
data (Map) : (optional) Key/Value data to send to the server.
callback (Callback) : (optional) Callback function invoked when the request completes (does not need to be successful).
2. $.getScript( url, [callback] ): Load and execute a JavaScript file via a GET request.
callback (Function) : (optional) Callback function after successful loading.
http://www.dbpoo.com/jquery-post-get-ajax-php/