PHP more and more applications, but also more and more extensive, in order to increase the richness of the site, resulting in a lot of new technology. Ajax is a modern web site can not be a lack of technology, he can refresh the data asynchronously, and achieve a lot of effects, such as the Refresh code, Micro Bo in the praise function, are the use of this.
The effect of this praise function diagram:
Home page file (index.php):
Copy Code code as follows:
<script type= "Text/javascript" src= "Http://www.jb51.net/js/jquery.min.js" ></script>
<script type= "Text/javascript" src= "Finger_ajax.js" ></script>
<?php
Header ("Content-type:text/html;charset=utf-8");
Include "finger_ajax.php";
$sql = "SELECT * from Finger_ajax";
$res = mysql_query ($sql, $link);
while ($row = Mysql_fetch_array ($res)) {
echo "<p>" $row [' title ']. "\r\n<a href= ' # ' onclick= ' finger (". $row [' id ']. ") ' > Praise (<span class= ' finger ". $row [' id ']." ' > ". $row [' finger ']." </span>) </a></p>\r\n ";
}
?>
Processing AJAX requests and configuration information files (finger_ajax.php):
Copy Code code as follows:
<?php
/** "Praise" function response to Ajax request * *
Configuration
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "DDDDDD";
$dbName = "Test";
$dbCharset = "UTF8";
$link = mysql_connect ($dbHost, $dbUser, $dbPass) or Die (Mysql_error ());
mysql_query ("Set names". $dbCharset);
mysql_select_db ($dbName);
End
Accept the corresponding ID
if (!empty ($_post[' id ')) {
$id = $_post[' id '];
"Praise" plus 1.
$sql = "Update Finger_ajax set finger=finger+1 where id= $id;";
if (mysql_query ($sql, $link)) {
echo "OK";
}else{
echo "Failed";
}
}
?>
JS file (finger_ajax.js):
Copy Code code as follows:
Praise JS
function Finger (topic_id) {
$.post ("finger_ajax.php", {"id": topic_id},
function (data) {
if (data== "OK") {
Alert ("Thank you for your support!") ");
}else{
Alert ("Sorry, failed!") ");
}
}, "text");
Get the current number of "praise" and add 1
var finger = parseint ($ (". Finger" +topic_id). HTML ()) +1;
Update "Praise" number of times
$ (". Finger" +topic_id). html (finger);
}
Database Code (FINGER_AJAX.SQL):
Copy Code code as follows:
DROP TABLE IF EXISTS ' Finger_ajax ';
CREATE TABLE ' Finger_ajax ' (
' id ' int (one) not NULL auto_increment,
' title ' varchar not NULL DEFAULT ',
' Finger ' int (one) not NULL DEFAULT ' 0 ',
PRIMARY KEY (' id ')
) Engine=myisam auto_increment=3 DEFAULT Charset=utf8;
-- ----------------------------
--Records of Finger_ajax
-- ----------------------------
INSERT into ' Finger_ajax ' VALUES (' 1 ', ' The weather is still good today! What do you want to do? ', ' 10 ');
INSERT into ' Finger_ajax ' VALUES (' 2 ', ' Welcome to Www.jb51.net, National Day will come, I wish you a happy National day!! ', ' 3 ');