使用AJAX简单地读取和写入数据库

分享于 

9分钟阅读

Web开发

  繁體
  • 下载源代码-35.3 KB
  • 为什么使用AJAX读取数据库?

    在ASP.NET中,数据库查询将需要回传。我从事过一个图像操作项目,在带宽和用户体验方面,回传代价是非常昂贵的,在这样的场景中,使用AJAX的好处远远超过了成本。

    Web应用程序的组件

    使用AJAX向web应用程序提供三个组件:

  • AjaxEngine
  • 这是没有用户界面的ASPX页,它执行所有服务器端函数,如数据库查找和更新。

  • AjaxClient
  • 这是一个JavaScript文件,它对AjaxEngine进行异步调用并将响应呈现回AjaxUI。

  • AjaxUI
  • 它执行简单的JavaScript任务,如在单击按钮时从AjaxClient调用函数。

    屏幕快照

    本示例使用Microsoft SQL Server的Norhtwind数据库使用AJAX检索和更新员工数据。输入1到9之间的雇员ID,然后单击Find检索数据,在文本框中进行更改,然后单击"Update Employee"以更新数据库记录。

    Sample screenshot

    单击"Update Employee"按钮时,AJAX用于更新Northwind中的雇员记录,并显示一条警告消息。

    Sample screenshot

    AjaxUI

    我们只需要处理Find和Update按钮的onClick事件,下面是代码:

    查找按钮:
    <inputtype="button"name="btnFindEmployee"class="btn"id=""value="Find"onclick="JavaScript:return btnFindEmpoyee_OnClick();">
    更新按钮:
    <INPUTid=""type="button"value="Update Employee"class="btn"name="btnUpdateEmployee"onclick="JavaScript:return btnUpdateEmpoyee_OnClick();">
    AjaxClient (JavaScript )

    以下是一些有趣的函数:

    //Creating and setting the instance of appropriate//XMLHTTP Request object to a"XmlHttp" variablefunction CreateXMLHTTP()
    {
     try {
     XMLHTTP = new ActiveXObject("Msxml2.XMLHTTP");
     }
     catch(e)
     {
     try {
     XMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
     }
     catch(oc)
     {
     XMLHTTP = null;
     }
     }
     //Creating object in Mozilla and Safariif(!XMLHTTP && typeof XMLHttpRequest!= "undefined")
     {
     XMLHTTP = new XMLHttpRequest();
     }
    }function btnFindEmpoyee_OnClick()
    {
     //Get Employee ID from text boxvar empID = document.getElementById("txtEmployeeID").value;
     // construct the URLvar requestUrl =AjaxEnginePage + "?Action=FindEmployee&EmpID=" + 
     encodeURIComponent(empID);
     CreateXMLHTTP();
     // If browser supports XMLHTTPRequest objectif(XMLHTTP)
     {
     //Setting the event handler for the response XMLHTTP.onreadystatechange = FindEmployee;
     //Initializes the request object with GET (METHOD of posting),//Request URL and sets the request as asynchronous. XMLHTTP.open("GET", requestUrl, true);
     //Sends the request to server XMLHTTP.send(null);
     }
    }function btnUpdateEmpoyee_OnClick()
    {
     //Get Employee ID from text boxvar empID = encodeURIComponent(document.getElementById("txtEmployeeID").value);
     var phone = encodeURIComponent(document.getElementById("txtPhone").value);
     var firstName = encodeURIComponent(document.getElementById("txtFirstName").value);
     var lastName = encodeURIComponent(document.getElementById("txtLastName").value);
     var title = encodeURIComponent(document.getElementById("txtTitle").value);
     var birthDate = encodeURIComponent(document.getElementById("txtBirthDate").value);
     var hireDate = encodeURIComponent(document.getElementById("txtHireDate").value);
     // construct the URLvar requestUrl =AjaxEnginePage + "?Action=UpdateEmployee&EmpID="+ empID + 
     "&FirstName="+ firstName +"&LastName="+ lastName + 
     "&Phone="+ phone +"&Title="+ title +"&BirthDate="+ 
     birthDate +"&HireDate="+ hireDate;
     CreateXMLHTTP();
     // If browser supports XMLHTTPRequest objectif(XMLHTTP)
     {
     //Setting the event handler for the response XMLHTTP.onreadystatechange = ShowSuccessMsg;
     //Initializes the request object with GET (METHOD of posting),//Request URL and sets the request as asynchronous. XMLHTTP.open("GET", requestUrl, true);
     //Sends the request to server XMLHTTP.send(null);
     }
    }function FindEmployee()
    {
     // To make sure receiving response data from server is completedif(XMLHTTP.readyState == 4)
     {
     //Valid Response is receivedif(XMLHTTP.status == 200)
     {
     SetEmployeeLabels(XMLHTTP.responseXML.documentElement);
     }
     else//something is wrong {
     alert("Could not retreive data from the server" );
     document.getElementById("lblFindEmployeeStatus").innerHTML="";
     }
     document.getElementById("btnFindEmployee").disabled=false;
     }
     else {
     document.getElementById("btnFindEmployee").disabled=true;
     document.getElementById("lblFindEmployeeStatus").innerHTML= 
     "<img src='Images/ajax-loader.gif'> loading...";
     }
    }
    AjaxEngine

    这是ASP.NET页面中的日常c#代码:

    privatevoid Page_Load(object sender, System.EventArgs e)
    {
     if(Request["Action"]!=null && Request["Action"].Trim()!="")
     {
     if(Request["Action"]=="FindEmployee" &&(Request["EmpID"]!=null && 
     Request["EmpID"].Trim()!=""))
     FindEmployee(Convert.ToInt32(Request["EmpID"]));
     elseif(Request["Action"]=="UpdateEmployee" &&(Request["EmpID"]!=null 
     && Request["EmpID"].Trim()!=""))
     UpdateEmployee(Convert.ToInt32(Request["EmpID"]), 
     Request["FirstName"],Request["LastName"],
     Request["Phone"],Request["Title"],Request["BirthDate"],Request["HireDate"]);
     }
    }publicvoid FindEmployee(int employeeID)
    {
     SqlConnection cnn=new SqlConnection(ConfigurationSettings.AppSettings["CnnStr"]);
     cnn.Open();
     SqlDataReader dr;
     SqlCommand cmd=new SqlCommand("SELECT EmployeeID, FirstName, LastName," + 
     "Title, BirthDate, HireDate,HomePhone" +
     " FROM Employees WHERE EmployeeID="+ employeeID,cnn);
     dr=cmd.ExecuteReader();
     if(dr.HasRows)
     {
     dr.Read();
     System.Text.StringBuilder sb=new System.Text.StringBuilder("");
     sb.Append("<Employee>");
     sb.Append("<EmployeeID><![CDATA["+ dr["EmployeeID"].ToString()+"]]></EmployeeID>");
     sb.Append("<FirstName><![CDATA["+ dr["FirstName"].ToString()+"]]></FirstName>");
     sb.Append("<LastName><![CDATA["+ dr["LastName"].ToString()+"]]></LastName>");
     sb.Append("<Phone><![CDATA["+ dr["HomePhone"].ToString()+"]]></Phone>");
     sb.Append("<Title><![CDATA["+ dr["Title"].ToString()+ "]]></Title>");
     sb.Append("<BirthDate><![CDATA["+ dr["BirthDate"].ToString()+ "]]></BirthDate>");
     sb.Append("<HireDate><![CDATA["+ dr["HireDate"].ToString() +"]]></HireDate>");
     sb.Append("</Employee>");
     Response.ContentType ="text/xml";
     Response.Write(sb.ToString());
     }
    }privatevoid UpdateEmployee(int employeeID,string firstName, string lastName,
     string phone,string title,string birthDate,string hireDate)
    {
     SqlConnection cnn=new SqlConnection(ConfigurationSettings.AppSettings["CnnStr"]);
     cnn.Open();
     SqlCommand cmd=new SqlCommand("UPDATE Employees Set FirstName='"+
     firstName +"', LastName='"+ lastName +"', HomePhone='"+ phone + 
     "', Title='"+ title +"', BirthDate='"+ birthDate +"', HireDate ='"+ 
     hireDate +"' WHERE EmployeeID="+ employeeID,cnn);
     cmd.ExecuteNonQuery();
    }

    在某些情况下,您需要使用AJAX完成繁琐的任务,例如数据库查找和更新。


    数据  Using  读写