Ajax Add data and delete article implementation code _AJAX related

Source: Internet
Author: User
Tags http request tagname
If you really have mastered the first few. Implementing the Ajax removal feature is as erratic as it can be. All I have to teach you is. Flexibility to use JavaScript and DOM to achieve a cool delete effect. Actually you learn to come here. It is already clear that the requested server Pages in Ajax technology are not much different in non-AJAX applications. But also accept the front-end sent over the request. Do some action in the background! After studying this tutorial. You will understand that you want to achieve a cool enough Ajax effect. You have to be proficient in the JavaScript Dom skills.
Just now I drank too much, and the above paragraph was written by me two days ago. I was going to go straight to bed. But I want to try. I can speak better after I drink.
In fact, I think that when I was drunk and blurred, I can impart my knowledge to you. Today's add effect is the same as adding data from the previous article. But today's removal may be the result you've never seen before. Want to delete that data. Please click on him. Then click the Delete button. This is not like a desktop application. Ajax is the magic of this. Otherwise he won't be pursued by web developers all over the world! Let's look at the examples first. You're going to be surprised!
Copy Code code as follows:

<title>ajax No refresh Add and delete data </title>
<style>
body{
font-size:12px;
}
table{
Border-collapse:collapse;

}
</style>
<body>
To show more fluency, we read only the latest 10 data in the database. Because the number of online testing is much. are operating on a database. Concurrency may occur!
Input: <input id= "str" type= "input"/> <input type= "button" value= "OK Add" onclick= "Add_post ()"/>
<span id= "msg" style= "color:red" ></span>
<table border= "1" ><!--This table is used to display data content-->
<tbody id= "a" ></tbody>
</table>
<span style= "color:red" > Action tip: Click the data you want to delete with your mouse. Then click Delete Button! </span>
<input id= "hid_id" type= "hidden"/>
<input type= "button" value= "delete data" onclick= "Del_data ()"/>
<script type= "Text/javascript" >
function Ajax_xmlhttp () {
Create XMLHttpRequest in IE, suitable for all versions above IE5.0
var msxmlhttp = new Array ("msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", " Microsoft.XMLHTTP ");
for (var i=0; i<msxmlhttp.length; i++) {
Try
{
_xmlhttp=new ActiveXObject (Msxmlhttp[i]);
}
catch (E)
{
_xmlhttp=null;
}
//loop to create XMLHTTP based on IE browser. end
If not IE browser, create a browser based on Firefox XMLHttpRequest
if (!_xmlhttp && typeof XMLHttpRequest!= "undefined")
{
_xmlhttp=new XMLHttpRequest ();
}
return _xmlhttp;
}

Reading data functions
function Read () {
var ajax = Ajax_xmlhttp (); Assigns a XMLHttpRequest object to a variable.
Ajax.open ("Post", "Add_del_data.asp?action=read", true);/Set the request mode, the requested Web page, the URL's action parameter is read, the asynchronous request
Ajax.onreadystatechange = function () {//You can also specify an already-written name
if (ajax.readystate = = 4) {//data returned successfully
if (Ajax.status =) {//http Request status code return OK
var xmlData = ajax.responsexml;//Receives the returned data in XML format and saves it in the XmlData variable
var list = xmldata.getelementsbytagname ("list")//in the returned data, get all list labels
if (list.length!=0) {
var t = document.getElementById ("a");//Get the table showing the data
while (t.rows.length!=0) {//When reading the data, if the table has been saved rows. Delete all
T.removechild (T.rows[0]);
}
for (Var i=0;i<list.length;i++) {
var tr = T.insertrow (t.rows.length);//A few lists add a few lines to the table.
Tr.setattribute ("id", list[i].childnodes[0].firstchild.nodevalue);
Tr.onclick = function (e) {add_event (e)};
var td = Tr.insertcell (0);
td.innerhtml = List[i].childnodes[1].firstchild.nodevalue;
}
}
}
}
}
Ajax.send (null);//commit request, parameter is NULL
}

Window.load = Read ();

function Add_event (e) {
E = e | | window.event;
var elem = E.target | | E.srcelement;
if (Elem.tagname = = "TD") {
Elem = Elem.parentnode;
}
var table = Elem.parentnode;
for (Var i=0;i<table.rows.length;i++) {
Table.rows[i].style.background= "";
}
Elem.style.background= "#999ccc";
document.getElementById ("hid_id"). Value = Elem.id;
}

Delete a data function
function Del_data () {
var mesage = document.getElementById ("msg");//Get span to display operation information
Mesage.innerhtml= "is removing please wait ...";
var table = document.getElementById ("a");//Get the table to display data
if (Table.rows.length = = 0) {
mesage.innerhtml = "There is no data in the table to delete!" ";
Return
}
var id = document.getElementById ("hid_id");
if (Id.value.length = = 0) {
mesage.innerhtml = "You have not selected the data!" ";
Return
}
var ajax = Ajax_xmlhttp ();//define XMLHttpRequest Object
Ajax.open ("Post", "Add_del_data.asp?action=del", true);/Set request mode, request file, asynchronous request

var param = "id=" +escape (id.value);//get ID to delete data

Ajax.onreadystatechange = function () {
if (ajax.readystate==4) {
if (ajax.status==200) {
var xml = Ajax.responsexml;
var msg = xml.getelementsbytagname ("msg") [0].firstchild.nodevalue;
if (msg = 0) {
mesage.innerhtml = "Successfully deleted data!" ";
var tr = document.getElementById (id.value);//Get the currently selected row
Tr.parentNode.removeChild (TR);//refers to the parent element of the row. Then delete the row.
Id.value= "";//delete complete empty text box values,
}
if (msg = 1) {
mesage.innerhtml = "Error occurred on service side, deletion failed!" ";
}
}
}
}
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Ajax.send (param);
}

Submit Data function
function Add_post () {
var Msgaes = document.getElementById ("msg");//To display a hint
var str = document.getElementById ("str");//Receive Input
if (Str.value.length = = 0) {
msgaes.innerhtml = "Do not accept empty content!" "
Return
}
Msgaes.innerhtml = "being submitted";
var ajax = Ajax_xmlhttp ();//define XMLHttpRequest Object
Ajax.open ("Post", "Add_del_data.asp?action=add", true);/Set request mode, request file, asynchronous request

var param = "str=" +escape (str.value);//Get what you entered, notice the STR here, the server will receive the value from Str.
Ajax.onreadystatechange = function () {
if (ajax.readystate==4) {
if (ajax.status==200) {
var msg = ajax.responseXML.getElementsByTagName ("msg");//Get the MSG label returned by the server
if (Msg[0].firstchild.nodevalue = = 0) {
var max_num = ajax.responseXML.getElementsByTagName ("Count") [0].firstchild.nodevalue;

var t = document.getElementById ("a");
var tr = t.insertrow (0);
Tr.setattribute ("id", max_num);
Tr.onclick = function (e) {add_event (e)};
var td = Tr.insertcell (0);
td.innerhtml = Str.value;
Str.value = "";
msgaes.innerhtml = "Add Complete";
}
else if (Msg[0].firstchild.nodevalue = 3) {
msgaes.innerhtml = "Do not accept empty content";
Return
}
else if (Msg[0].firstchild.nodevalue = 1) {
msgaes.innerhtml = "Error occurred on server, data addition failed!" ";
Return
}
else{
msgaes.innerhtml = "This instance is for learning to use." Please do not enter maliciously. Thank you! ";
}
}
}
}
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");//Note submitting data to the server, you must set the header. Otherwise, the service side will not receive
Ajax.send (param);/Note the Send method submits the contents of the Param variable to the server.
}
</script>
<a href= "http://www.jb51.net" target= "_blank" > cloud-dwelling Community +</a>
</body>

What about the effect is not very cool? The above text box is the foreground HTML source code. Let's start by talking about what we did on the front end. Start with the body tag.


A hint of the text of a friendship. Tell you what will happen!
Add text boxes and buttons to the data! Used to write data content to the server-side database.
A span label. ID is msg, used to display information about your current operation
a table. There are tbody elements in the table with ID a. Used to display the data read. You can select the data you want to delete in the form.
A hidden input box. When you select the data. The ID value of the data is placed in the input box. This value is referenced when deleting. Submit to the service side
Deletes the data push button. Defines an onclick click event. Del_data () function. Send a delete directive to a service
Below enter script foot part. There are 5 custom functions inside the script. respectively: Ajax_xmlhttp (), Read (), Add_event (), Del_data (), Add_post (). Let's one by one explain the function.

1, Ajax_xmlhttp (), create an available XMLHttpRequest object, if you do not know what is XMLHttpRequest, see: XMLHttpRequest
2, read (), reading the data function. Ajax read data has been mentioned in previous tutorials. I only talk about the focus of today's reading process, first look at the output of the server-side page XML. Add_del_data.asp?action=read. After retrieving all the list tags from the XML data returned from the server. We first use the getElementById method to get the table that holds the data. Then loop through the list tags. Each list represents a single piece of data. Each list contains 2 child elements. The ID value of the data is stored in the 1th child element, and the text content of the data is stored in the 2nd child element. OK, let's take a look at the statements in the For loop in the Read () function:
(1): var tr = t.insertrow (t.rows.length); each cycle of a list adds one row to the table. Because each row of the table displays a single piece of data. and returns a reference to the row.
(2): Tr.setattribute ("id", list[i].childnodes[0].firstchild.nodevalue); set an id attribute for the new row. and specify a value for the property. Note that this is the point. List[i].childnodes[0].firstchild.nodevalue the meaning of this sentence is to get the value of the ID field in each piece of data. That is, the ID value of the piece of data. We write this value to the TR ID attribute. To make it easier for us to click on a line with the mouse to later reference this ID.
(3): Tr.onclick=function (e) {add_event (e)}; then bind a custom function to the new row. The name of the function is add_event ();
(4): Var Td.tr.insertCell (0); Add a column to the new addition. and returns a reference to the column.
(5): td.innerhtml = List[i].childnodes[1].firstchild.nodevalue; writes the text contents of the 2nd child element of the first list in this column. Which is the Content field.
We set each data ID to the id attribute of each row in the table. Fill in the cells in each row with the text from the content in each piece of data. The entire data display process is complete!
 
3, Add_event (e); We bound the function to each row of the table within the Read function. The event object is passed to addevent using the closure technology. The function is to find the line that you clicked. and obtain the ID of the row data:
(1): E = e | | Window.event, standardizing event objects. FF and other browsers using parameter transfer, IE can directly use window.event.
(2): var elem = E.target | | E.srcelement; See also: Target or srcelement. Standardize the element that triggers the event. Is the element that triggered the event. The idea here is that you clicked on the line in the table. But I actually took TD instead of TR. This should be the result of legendary event capture and bubbling. It's okay we use tagname to judge if it is TD, then take the TD's parent element. It must be TR now. Oh
(3): var table = Elem.parentnode; takes the parent element of tr. That's the tbody. and returns a reference to the tbody.
(4): Use a For loop to iterate through all the rows in the tbody. Set the background color of each row to blank.
(5): elem.style.background= "#999000", after the cycle is complete. Add a background color to the line you clicked on.
(6): document.getElementById ("hid_id"). Value = elem.id; Gets the hidden text box in the Web page. and write the ID of the line you clicked into the text box. The id attribute value of the row. It is you who selected the ID value of the data. And each click on one line. The values in this text box will change as you click on the line. And we are in the function of submitting the deletion is the value in the text box referenced.

4, Del_data (); the function: The ID of the deleted data is submitted to the Web page of the server request. Then a MSG label is returned based on the service side. To determine if the data was successfully deleted. I only talk about things that I haven't been involved in before:
(1): Click the Delete button to enable the Del_data () function. Let's first find the span label with the ID MSG. Then write a piece of operational information. Tell you that you are deleting data.
(2): Gets the table where the data is to be stored. Which is the tbody with ID a. Determine if there is data in the tbody. If there is no data in the tbody. Tells you that there is no data to choose from. Then exit the function. No more down execution.
(3): Get the hidden text box. and determine if the text box has a value. Displays a hint message if it is empty. Exits the function. No more execution! If a value exists, you are choosing a particular piece of data. The following Ajax will submit your chosen data to the server page for deletion
(4): How Ajax is submitted and recycled data. See "Ajax preliminary reading Data" and "Ajax reads to table."
(5): Del_data () Focus here: Judge the service end to return the MSG tag. If the content of the label is 0, the service side works all right, the data has been successfully deleted.
(6): After the data is successfully deleted: var tr = document.getElementById (id.value); Gets the currently selected row.
(7): Tr.parentNode.removeChild (TR);//reference the parent element of the row tbody, delete the row!
This deletes the data complete. The pass is the signal that receives the service end sends back. If the deletion succeeds, deletes the table row selected at the front end. Give a hint if it fails!
5, Add_post (); This function is basically the same as in the previous article. Submit the added data to the server. The only difference is that after the data has been successfully added. We then called the Read () function to read the new data. Because we have to get the correct ID of the newly added data so that we can delete it correctly!
Well, the front end of the code has been explained.
The following is the source of the server Web page requested by this Ajax example tutorial:
Copy Code code as follows:

<!--#include file= "conn.asp"-->
<%
' From: Http://Www.Web666.Net
' Author: Kang Dong
' If you want to reprint, please be sure to keep the above information
' Define a variable to hold the XML data
Xml= "<?xml version= ' 1.0 ' encoding= ' gb2312 '?><body> '"
Action=request.querystring ("action") ' uses Get method to accept an action to determine what the client wants to do
Select Case Action
Case "read" ' If Read is performed
Call Read
Case "Add" if you add data for add
Call Add_data
Case "Del" If the delete data is performed on the Del
Call Del_data
Case Else
XML = xml& "<msg> Request parameter error, please do not attempt illegal operation!" </msg> "
End Select
xml=xml& "</body>"
Response.Clear
Response.contenttype= "Text/xml"
response.charset= "gb2312"
Response.Write XML
Response.End


Sub read ' defines a process for reading data
Call openconn ' Open database link
SQL = "SELECT top * from del_table ORDER BY id DESC" ' Open the table named Del_table in the database
Set Rs = conn.execute (SQL) ' executes the SQL statement and assigns the SQL index to the Rs variable

While not rs.eof ' if there is data in the table. The loop reads all the time
XML = xml& "<list>" creates a list label for each data read
XML = xml& "<id>" &rs ("id") & "</id>" ID field contents
XML = xml& "<content>" &rs ("Content") & "</content>" content field contents
XML = xml& "</list>" closes the list label every time you finish reading a piece of data
Rs.movenext ' performs the next reading of a piece of data
Wend ' If there is no data in the database. Then end the loop
Close_conn ' Close Database link
End Sub

Sub add_data ' Add data procedure
On Error Resume Next ' If an error continues to execute the program
Openconn ' Open Database link

str = Trim (Request.Form ("str")) ' receives the STR content transmitted by the client
If str = "" Then
XML = xml& ' <msg>3</msg> ' if the content being submitted is empty. Return 3
Exit Sub ' exits procedure
End If

SQL = "Insert into del_table (content) VALUES (' &str& ')"
Conn.execute (SQL) ' Execute Add data
If Err.Number = 0 Then ' To determine if any errors occurred,
XML = xml& "<msg>0</msg>" If no errors occur, the proof data is successful. return 0
Else
XML = xml& "<msg>1</msg>" If an error occurs. It proves that there is an error. Data is likely to add failure
End If
Close_conn
End Sub

Sub del_data ' Delete data procedure
On Error Resume Next
Openconn
id = Request ("id")
SQL = "Delete from del_table where id=" &id
Conn.execute (SQL)
If Err.Number = 0 Then
XML = xml& "<msg>0</msg>"
Else
XML = xml& "<msg>1</msg>"
End If
Close_conn
End Sub
%>

I am using the ASP output XML format data technology on the server side. I have explained in the previous several. You can use php,.net,jsp to easily simulate it.
(!--#include file= "conn.asp"-) is my database link file. For security I do not disclose the name of the database. The table name read this time is: del_table field: id,content
This is the place to talk today, what you don't understand. Please add AJAX Technology Group: 110167482
The next article we say: Ajax read the data page display Chapter
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.