ajax 无刷新添加和删除数据
本例是ajax无刷新提交表单,无刷新删除记录,可以用于评论,当然本例只是一个最基本的案例,具体的要在实际中添加多一些字段
数据库结构
CREATE TABLE `add_delete_record` (
`id` int(11) NOT NULL auto_increment,
`content` varchar(5) character set utf8 collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
index.php
js文件
JavaScript Code复制内容到剪贴板
- <script type="text/javascript">
- $(document).ready(function() {
- //##### send add record Ajax request to response.php #########
- $("#FormSubmit").click(function (e) {
- e.preventDefault();
- if($("#contentText").val()==='')
- {
- alert("请输入内容!");
- return false;
- }
- var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
- jQuery.ajax({
- type: "POST", // HTTP method POST or GET
- url: "response.php", //Where to make Ajax calls
- dataType:"text", // Data type, HTML, json etc.
- data:myData, //Form variables
- success:function(response){
- $("#responds").append(response);
- $("#contentText").val(''); //empty text field on successful
- },
- error:function (xhr, ajaxOptions, thrownError){
- alert(thrownError);
- }
- });
- });
- //##### Send delete Ajax request to response.php #########
- $("body").on("click", "#responds .del_button", function(e) {
- e.returnValue = false;
- var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
- var DbNumberID = clickedID[1]; //and get number from array
- var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
- jQuery.ajax({
- type: "POST", // HTTP method POST or GET
- url: "response.php", //Where to make Ajax calls
- dataType:"text", // Data type, HTML, json etc.
- data:myData, //Form variables
- success:function(response){
- //on success, hide element user wants to delete.
- $('#item_'+DbNumberID).fadeOut("slow");
- },
- error:function (xhr, ajaxOptions, thrownError){
- //On error, we alert user
- alert(thrownError);
- }
- });
- });
- });
- </script>
主要代码
XML/HTML Code复制内容到剪贴板
- <div class="content_wrapper">
- <ul id="responds">
- <?php
- //include db configuration file
- include_once("conn.php");
- //MySQL query
- $Result = mysql_query("SELECT id,content FROM add_delete_record");
- //get all records from add_delete_record table
- while($row = mysql_fetch_array($Result))
- {
- echo '<li id="item_'.$row["id"].'">';
- echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
- echo '<img src="images/icon_del.gif" border="0" />';
- echo '</a></div>';
- echo $row["content"].'</li>';
- }
- ?>
- </ul>
- <div class="form_style">
- <textarea name="content_txt" id="contentText" cols="45" rows="5" ></textarea>
- <button id="FormSubmit">添加</button>
- </div>
- </div>
response.php
PHP Code复制内容到剪贴板
- <?php
- //include db configuration file
- include_once("conn.php");
- if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0)
- { //check $_POST["content_txt"] is not empty
- //sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
- $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
- // Insert sanitize string in record
- if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')"))
- {
- //Record was successfully inserted, respond result back to index page
- $my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
- echo '<li id="item_'.$my_id.'">';
- echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">';
- echo '<img src="images/icon_del.gif" border="0" />';
- echo '</a></div>';
- echo $contentToSave.'</li>';
- }else{
- //header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
- header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
- exit();
- }
- }
- elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
- { //do we have a delete request? $_POST["recordToDelete"]
- //sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
- $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
- //try deleting record using the record ID we received from POST
- if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete))
- {
- //If mysql delete query was unsuccessful, output error
- header('HTTP/1.1 500 Could not delete record!');
- exit();
- }
- }
- else
- {
- //Output error
- header('HTTP/1.1 500 Error occurred, Could not process request!');
- exit();
- }
- ?>
原文地址:http://www.freejs.net/article_biaodan_14.html