Real-time display of Ajax data modification implementation code

Source: Internet
Author: User

The server webpage we are requesting this time is: Edit_Data.Asp. I will provide the source code of this asp file in this ajax tutorial.
In fact, it is easy for you to modify data when you learn how to use ajax to add data! Let's talk about the front-end JavaScript code and the effect of this ajax instance!

Copy codeThe Code is as follows: <Head>
<Title> modify data using ajax </title>
<Style>
Body {
Font-size: 12px;
}
</Style>
</Head>
<Body>
<P> there are many concurrent online tests, and sometimes concurrent modifications may occur. </p>
<Hr/>
<Table border = "1">
<Thead> <tr> <td> data id </td> <td> data content </td> </tr> </thead>
<Tbody id = "a"> <! -- Tbody used to store content -->
</Tbody>
</Table>

Input No.: <input id = "data_id" type = "text"/> <br/>
Modification content: <input id = "data_content" type = "text"/> <br/>

<Input type = "button" value = "confirm to modify" onclick = "Edit_Data ()"/>
<Span id = "msgaes" style = "color: red"> </span>
<Script type = "text/javascript">
Function ajax_xmlhttp (){
// Create xmlhttpRequest in IE for all IE5.0 and later versions
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;
}
} // Cyclically create xmlhttp. End Based on IE browser
// If not, create xmlhttpRequest Based on FireFox and other browsers
If (! _ Xmlhttp & typeof XMLHttpRequest! = "Undefined ")
{
_ Xmlhttp = new XMLHttpRequest ();
}
Return _ xmlhttp;
}

// Read data Functions
Function Read (){
Var ajax = ajax_xmlhttp (); // assign the xmlhttprequest object to a variable.
Ajax. open ("post", "Edit_Data.asp? Action = read ", true); // sets the request method, the requested webpage, And the url's action parameter is read, asynchronous request
Ajax. onreadystatechange = function () {// You can also specify a name for the function that has been written.
If (ajax. readyState = 4) {// data returns success
If (ajax. status = 200) {// Return OK for the http Request status code
Var xmlData = ajax. responseXML; // receives the returned data in xml format and stores it in the xmlData variable.
Var list = xmlData. getElementsByTagName ("list"); // obtain all list tags from the returned data.
If (list. length! = 0 ){
Var t = document. getElementById ("a"); // obtain the table that displays the data.
For (var I = 0; I <list. length; I ++ ){
Var tr = t. insertRow (); // Add several rows to the table if there are several lists.
For (var k = 0; k <list [I]. childNodes. length; k ++) {// traverse sub-elements in each list
Var td = tr. insertCell (); // each list contains several sub-elements, which add several columns to a row
Td. innerHTML = list [I]. childNodes [k]. firstChild. nodeValue; // write the text content in the k sub-element of list I in the cell
}
}
}
}
}
}
Ajax. send (null); // submit the request. The parameter is null.
}
Window. load = Read ();

// Function for modifying data
Function Edit_Data (){
Var msgaes = document. getElementById ("msgaes"); // displays information about the current operation.
Var id = document. getElementById ("data_id"); // obtain the data id to be modified
Var content = document. getElementById ("data_content"); // get the modified content
If (id. value. length = 0 | content. value. length = 0 ){
Msgaes. innerHTML = "No. Or the content cannot be blank! ";
Return;
}
// The following row assigns the value of id and content to the param variable, and then uses the send method to submit the param
Var param = "id =" + escape (id. value) + "& content =" + escape (content. value );
Var ajax = ajax_xmlhttp ();
Ajax. open ("post", "Edit_Data.asp? Action = edit ", true );
Ajax. onreadystatechange = function (){//
If (ajax. readyState = 4 ){
If (ajax. status = 200 ){
Var xmlData = ajax. responseXML;

Var msg = xmlData. getElementsByTagName ("msg ");
If (msg. length! = 0 ){
Switch (msg [0]. firstChild. nodeValue) {// judge the msg Value
Case "0": msgaes. innerHTML = "data modified! ";
Var a = document. getElementById ("");
For (var I = 0; I <a. rows. length; I ++) {// traverse each column in the table. This method is a bit dumb.
For (var k = 0; k <a. rows [I]. cells. length; k ++ ){
If (a. rows [I]. cells [0]. innerHTML = id. value ){
A. rows [I]. cells [1]. innerHTML = content. value;
Id. value = "";
Content. value = "";
Return;
}

}
}
Break;
Case "1": msgaes. innerHTML = "An error occurred while writing data to the server! ";
Break;
Case "3": msgaes. innerHTML = "Please enter the correct data number and modification content! ";
Break;
Case "4": msgaes. innerHTML = "the data number you entered does not exist in the Database. Please enter it again! ";
Break;
Default: msgaes. innerHTML = "an unknown error occurred! Contact the author: QQ30458885 ";
Break;
}
}
}
}
}
Ajax. setRequestHeader ("content-type", "application/x-www-form-urlencoded ");//
Ajax. send (param );
}
</Script>
</Body>
</Html>

We will analyze the above ajax front-end code. There are three functions in the Code: ajax_xmlhttp (), Read (), Edit_Data (). We will explain their functions in turn.

1. alax_xmlhttp (): used to create an available XMLHTTPRequest object. If you do not know what XMLHTTPRequest is, refer to: XMLHTTPRequest object details.
2. Read (): Read data function, used to Read existing data in the server database. this function is basically similar to the previous data reading functions. I will not repeat the similarities. if you do not understand. please refer to the previous ajax series tutorials! It is only slightly different in parsing after xml data is returned. First, let's take a look at the format of data read by the server: Edit_Data.Asp? Action = read. there are five list tags in the xml data output by the server. this indicates that there are 5 data records in the database. each list tag contains two sub-elements: id and content. this is the content of each piece of data in the database. id field and content field. understand these. let's talk about how the Read function parses the returned xml data. from list = xmlData. start with getElementsBytagName ("list"). First, use if to determine whether the list tags are successfully obtained. if yes, obtain the table of the displayed data. then use for to traverse these lists. A list in each loop adds a row to the table where data is to be displayed, because each list contains a piece of data. each row of our table must display a piece of data. after each row is created. then we use a for to traverse the child elements of the current list. each time a child element is traversed, a column is added for the row. then write the text content of the k sub-element in the current list to this column. first column The content in the response id corresponds to the content in the second column. If you still don't understand what I will talk about, please fill in the javascript for loop! And Related Dom commands. The Dom manual provided on this site has a detailed explanation of each instruction!
3. Edit_Data (): This function is used to submit the data number you entered and the data content to be modified. as long as the data is successfully submitted. no matter what happens. the server returns a msg tag. the Edit_Data function receives the returned msg tag. determine data modification based on the content of the msg label. the Add_Data function in the previous "ajax add data" tutorial is basically the same. if you have any questions. please refer to the ajax data adding tutorial in the previous article. I will focus on how the Edit_Data function instantly displays the modified content in the table! From msg = xmlData. start with getElementsByTagName ("msg. first, if to determine whether msg exists. if you have obtained the msg tag. the Modification result of the server is determined based on the content in the msg label. if the msg content is 0, the data is successfully modified. In this case, find the row you entered in the table that displays the data on the front end. then write the modified data you entered into the second column of the row. at this time, we have not read the data in the database again! If you have any questions, refer to the previous tutorial.

The following is the source code of the Edit_Data.Asp file on the server:Copy codeThe Code is as follows: <! -- # Include file = "Conn. Asp" -->
<%
'From: http://Www.Web666.Net
'Author: Kang Dong
'The above information must be retained if reprinted
'Define a variable to save xml data.
Xml = "<? Xml version = '1. 0' encoding = 'gb2312 '?> <Body>"
Action = Request. QueryString ("action") 'accepts an action in get to determine what operations the client wants to perform.
Select case action
Case "read" 'if it is read, the data read operation is performed.
Call Read
Case "edit" 'if it is edit, modify the data
Call Edit_Data
Case else
Xml = xml & "<msg> the request parameter is incorrect. Please do not try to operate it illegally! </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 the database link
SQL = "Select * From edit_table" 'Open the table named web_table in the database.
Set Rs = Conn. Execute (SQL) 'executes the SQL statement and assigns the index value to the rs variable.

While Not Rs. Eof 'If the table contains data, it will be read cyclically
Xml = xml & "<list>" 'creates a list tag for each piece of data read.
Xml = xml & "<id>" & Rs ("id") & "</id>" 'id field content
Xml = xml & "<content>" & Rs ("content") & "</content>" 'content field content
Xml = xml & "</list>" 'the list tag is closed every time a piece of data is read.
Rs. MoveNext execute the next data read.
Wend' if no data exists in the database, the loop ends.
Close_conn' close the database link
End Sub

Sub Edit_Data
On Error Resume Next 'ignore Error
Openconn' open the database link
Id = Trim (Request. Form ("id") 'receives the id data from the client.
SQL = "Select * From edit_table Where id =" & id
Set Rs = Conn. Execute (SQL)
If Rs. Eof then
Xml = xml & "<msg> 4 </msg>"
Exit Sub
End If
Content = Trim (Request. Form ("content") 'receives the modified content
If id = "" Or content = "" then' If one of id Or content is null, 3 is returned.
Xml = xml & "<msg> 3 </msg>"
Exit Sub 'exit
End If
SQL = "Update edit_table Set content = '" & content & "'where id =" & id
Conn. Execute (SQL) 'executes the SQL statement for modifying data

If Err. Number = 0 then', If no error occurs
Xml = xml & "<msg> 0 </msg>" 'Add a msg tag with the content 0

Exit Sub 'exit
Else' if an error occurs
Xml = xml & "<msg> 1 </msg>" 'if an error occurs, add the msg tag with the content 1
Exit Sub 'exit
End If
End Sub
%>

The database table used in the source code of asp is: edit_table, which has the following fields: id and content. the table contains five data entries: html, css, dom, javascript, and ajax. the source code is explained in detail in the previous ajax tutorial!
Reminder: This ajax tutorial is series-based. to reduce the length of space. we will not repeat the learned content in each tutorial. if you are a beginner, start with ajax. learn one by one! Thank you for your cooperation!
Next article: "ajax addition and deletion"
This article copyright: Web circle first address: http://Www.Web666.Net

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.