实现AJAX局部刷新以及PageMethod方法的使用
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="../Scripts/jquery-2.1.1.js"></script> <script type="text/javascript"> //1. 使用PageMethod 方法 function GetBankName1() { var Account = document.getElementById("TextBox1").value; PageMethods.GetBankNameByAccount(Account, onSucceed); } function onSucceed(result) { document.getElementById("Label1").innerText = result; } //2. 使用AJAX 一部刷新 function GetBankName2() { var Account = $("#TextBox1").val(); $.ajax({ type: "Post", url: "GetDataFromDB.aspx/GetBankNameByAccount", //data: "{‘Account‘:‘" + Account + "‘,‘Name‘:‘" + 456 + "‘}", data: "{‘Account‘:‘" + Account + "‘}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { document.getElementById("Label1").innerText = data.d; } }); } //3. 使用一般的XML请求 function GetBankName3() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange = function (data) { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //document.getElementById("Label1").innerText = xmlhttp.responseText; alert(data); } } var Account = document.getElementById("TextBox1").value; xmlhttp.open("post", "GetDataFromDB.aspx/GetName", true); xmlhttp.send(); } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> Account Number: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> Bank Name:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <br /> <input id="Button1" type="button" value="Use Page Method" onclick="GetBankName1();" /><br /> <input id="Button2" type="button" value="Use AJAX" onclick="GetBankName2();" /> <input id="Button3" type="button" value="Use XML Request" onclick="GetBankName3();" /> </div> </form> </body> </html>
后台代码:
public partial class GetDataFromD : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label2.Text = DateTime.Now.ToString();//检测是否实现了局部刷新 } [WebMethod] public static string GetBankNameByAccount(int Account) { string BankName = ""; using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString)) { conn.Open(); string sql = "select Name from customers where id=@Account"; SqlCommand cmd = new SqlCommand(sql,conn); SqlParameter p = new SqlParameter("@Account",Account); cmd.Parameters.Add(p); using (SqlDataReader r = cmd.ExecuteReader()) { if(r.Read()) { BankName= r[0].ToString(); } } } return BankName; } [WebMethod] public static string GetName() { return "Hello"; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。