Ajax modify the data to display the real time code _ajax related

Source: Internet
Author: User
The server-side page We are requesting this time is: edit_data.asp I will provide the source code for this Asp file in this Ajax tutorial.
In fact, when you learn how to use Ajax to add data, it's easy for you to make changes to your data. Crap don't say first look at the front end of the JavaScript code and this time Ajax instance effect!

Copy Code code as follows:

<title>ajax Modify Data </title>
<style>
body{
font-size:12px;
}
</style>
<body>
<p> There are many people who test online at the same time, and sometimes there may be concurrent modifications. </p>
<table border= "1" >
<thead><tr><td> Data number </td><td> data content </td></tr></thead>
<tbody id= "A" ><!--for storing content tbody-->
</tbody>
</table>

Input number: <input id= "data_id" type= "text"/><br/>
Content modified: <input id= "data_content" type= "text"/><br/>

<input type= "button" value= "OK Modify" onclick= "Edit_data ()"/>
<span id= "Msgaes" style= "color:red" ></span>
<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", "Edit_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
for (Var i=0;i<list.length;i++) {
var tr = T.insertrow ();//A few lists add a few lines to the table.
for (Var k=0;k<list[i].childnodes.length;k++) {//traversal of child elements in each list
var td = Tr.insertcell ();//A few child elements in each list, add a few columns to one line
td.innerhtml = list[i].childnodes[k].firstchild.nodevalue;//Writes the text contents of the K child element in the first list in a cell
}
}
}
}
}
}
Ajax.send (null);//commit request, parameter is NULL
}
Window.load = Read ();

function to modify data
function Edit_data () {
var Msgaes = document.getElementById ("Msgaes");//To display some current action information
var id = document.getElementById ("data_id");//Get the data number to modify
var content = document.getElementById ("data_content");//Get the modified contents
if (id.value.length = 0 | | content.value.length = = 0) {
msgaes.innerhtml = "number or content is not allowed to be empty!";
Return
}
The following line assigns the value of the ID and content to the Param variable and then submits the param with the Send method
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) {//To determine the value of MSG
Case "0": msgaes.innerhtml = "Modify data Success!" ";
var a = document.getElementById ("a");
for (Var i=0;i<a.rows.length;i++) {//Traverse each column of the table. This method is a little stupid.
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 = "Server side error writing data!" ";
Break
Case "3": msgaes.innerhtml = "Please fill in the correct data number and modify the content!" ";
Break
Case "4": msgaes.innerhtml = "Database does not exist the data number you entered, please re-enter!" ";
Break
Default:msgaes.innerHTML = "Unknown error occurred!" Please contact Author: QQ30458885 ";
Break
}
}
}
}
}
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Ajax.send (param);
}
</script>
</body>


Let's analyze the code above the Ajax front end. There are three functions in the code. respectively: Ajax_xmlhttp (), Read (), Edit_data (). We'll explain their role in turn.

1, Alax_xmlhttp (): To create a usable XMLHttpRequest object, if you do not know what is XMLHttpRequest, please refer to: XMLHttpRequest Object detailed
2, read (): Read the data function to read the existing data in the server-side database. This function is basically the same as the previous reading data functions. I don't repeat the same thing. If you don't understand. See the previous series of Ajax tutorials! Only slightly different in parsing after returning the XML data. First look at the service-side read data format: Edit_data.asp?action=read. There are 5 list tags in the server-side output XML data. This means that there are 5 data in the database. And each list label under the bread contains ID and content two child elements. This is the content of every piece of data in the database. ID fields and content fields. Understand these. Let's say how the Read function parses these returned XML data. From the beginning of List=xmldata.getelementsbytagname ("list"), first use if to determine if these list tags have been successfully obtained, and if so, get the table in which we display the data. And then use for to iterate through these list. Each cycle of a list adds a row to the table where we want to display the data, because each list contains a single piece of data. And each row of our table displays a single piece of data. Then after each line is created. We then use a for to traverse the child elements of the current list. Each child element is traversed to add a column to the row. The column is then written to the text content of the K child element in the current list. The first column corresponds to the contents of the ID, and the second column corresponds to the contents of the content. If you don't understand what I'm talking about. Please fill in the JavaScript for loop! and the DOM related instructions involved. The DOM manual provided by 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 content of the data to be modified. As long as the data is submitted successfully. No matter what happens. The server will return a msg label. The Edit_data function receives the returned MSG label. Based on the contents of the MSG label to determine the situation of data modification. The Add_data function in the previous "Ajax Add Data" tutorial is basically the same. If there is a point of no understanding. Please refer to the previous AJAX Add data tutorial. I'll focus on how the Edit_data function will instantly display the modified content to the table! Start with Msg=xmldata.getelementsbytagname ("MSG"). First if the MSG exists is judged. If the MSG label has been obtained. The results of changes to the server are judged based on the contents of the MSG label. MSG content is 0 for the data was successfully modified, then we find the line in the table where you entered the number on the front end of the display data. Then write the modified data you entered into the second column of the row. At this point we do not read the data in the database repeatedly! If you have any doubts, please refer to the previous tutorial.

The following is the source of the server's edit_data.asp file:
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 "Edit" if the Modify data operation is performed for edit
Call Edit_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 * from Edit_table" ' opens a table with the name web_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 Edit_data
On error Resume Next ' Ignore error
Openconn ' Open Database link
id = Trim (request.form ("id")) ' receives the ID data number sent by 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 modified contents
If id = "" Or content = "Then" returns 3 if ID or content has an empty entry
XML = xml& "<msg>3</msg>"
Exit Sub ' exits procedure
End If
SQL = "Update edit_table Set content= '" &content& "Where id=" &id
Conn.execute (SQL) ' executes the SQL statement that modifies the data

If Err.Number = 0 Then ' If no error occurred
XML = xml& "<msg>0</msg>" add a msg tag with content of 0

Exit Sub ' exits procedure
Else ' If any errors occur
XML = xml& "<msg>1</msg>" ' If any errors occur, add MSG tags, content is 1
Exit Sub ' exits procedure
End If
End Sub
%>

The ASP's source code used in the database table is: Edit_table field, respectively: Id,content. There are 5 pieces of data in the table: Html,css,dom,javascript,ajax. The source of knowledge in the previous AJAX tutorial has a detailed explanation!
Friendly reminder: This AJAX tutorial is a series of sex. To reduce space. We do not repeat what we have learned in each tutorial. If you are a beginner, start preparing the article from Ajax. Learn by yourself! Thank you for your cooperation!
Next we say: "Ajax Add and delete articles"
This article Copyright: Web Circle Starting 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.