閑來無事,把最近使用Ajax無刷新開發的一些知識整理一下,一邊回顧:
項目一:修改密碼
HTML代碼:
<input id="txtOriginalPass" type="text" />
<input id="txtNewPass" type="text" />
<input id="txtConfirmPass" type="text" />
<input id="btnSubmit" type="button" value="確認" onclick="ConfirmChange()" />
<input id="btnCancel" type="button" value="取消" />
js腳本:
<script type="text/javascript">
function ConfirmChange() {
$.ajax({
type: "POST", //頁面請求的類型,通常使用POST,那么處理頁需要使用Request.Form["參數名稱"]來獲取頁面傳遞的參數
url: "UpdatePasswordOfUser.ashx", //處理頁的相對地址
data: { OriginalPass: $('#txtOriginalPass').val(), NewPass: $('#txtNewPass').val(), RePass: $('#txtConfirmPass').val() },
success: function (msg) { //這是處理后執行的函數,msg是處理頁返回的數據
alert(msg);
}
});
}
</script>
ashx處理頁面的代碼:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string OriPass = context.Request.Form["OriginalPass"]; //原始密碼(Get傳參對應QueryString)
string txtNewPass = context.Request.Form["NewPass"]; //新密碼
string txtConfirmPass = context.Request.Form["RePass"]; //確認密碼
/*-----這里可以寫調用的函數------*/
context.Response.Write("密碼修改成功"); //返回信息
}
項目二:兩個DropDownList下拉列表無刷新的聯動:
對於第一個DropDownList顯示的數據,實在頁面加載的時候賦的數據源,當這個DropDownList選項發生變化時,把數據發送到處理頁,
然后處理頁返回數據給第二個DropDownList
HTML代碼:
<asp:DropDownList ID="ddlDeptNameOfSign" runat="server" Width="200px" onchange="GetChildDrop()"></asp:DropDownList>
<asp:DropDownList ID="ddlUserOfSign" runat="server" Width="200px" onchange="GetChildItem()"></asp:DropDownList>
js腳本:
<script type="text/javascript">
//頁面加載時進行下拉列表的初始化
$(document).ready(function () {
var childDrop = "<%=ddlUserOfSign.ClientID %>"; //人員
$('#' + childDrop).append("<option value='0'>---請選擇簽約人員---</option>"); //此處的value為0,為了數據處理方便,建議不要省略
})
//頁面加載的時候,綁定下拉列表:簽約部門、簽約人員
function GetChildDrop() {
var parentDrop = "<%=ddlDeptNameOfSign.ClientID %>"; //部門
var childDrop = "<%=ddlUserOfSign.ClientID %>"; //人員
$('#' + childDrop + ' option').remove();
$.ajax({
type: "POST",
url: ".../Pages/DepartmentUserOfSign.ashx",
data: { "parentDrop": $('#' + parentDrop).val() },
success: function (data) {
if (data != "") {
var returnValue = data.split(",");
$('#' + childDrop).append("<option value='0'>---請選擇簽約人員---</option>");
$('#' + childDrop + ' option:first').attr('selected', 'true');
for (var i = 0; i < returnValue.length - 1; i++) {
if (i % 2 == 0) {
$('#' + childDrop).append("<option value=" + returnValue[i] + ">" + returnValue[i + 1] + "</option>");
$('#' + childDrop).val(returnValue[i+1]);
}
}
}
else {
alert("沒有對應的簽約人員.");
}
}
});
}
//當子列表改變選項時,發送到處理頁面,用於記憶選中的值,用這種方法有點猥瑣,但是無刷新時加載的數據在.NET頁面的后台是獲取不到的
function GetChildItem() {
var childDrop1 = "<%=ddlUserOfSign.ClientID %>"; //人員
$.ajax({
type: "POST",
url: ".../Pages/handleLoginNameOfContract.ashx",
data: { "childDrop": $('#' + childDrop1).val() },
success: function (data) {
}
});
}
</script>
ashx處理頁面代碼:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string departmentValue = context.Request.Form["parentDrop"];
if (!string.IsNullOrEmpty(departmentValue))
{
//不為空
string sql = "select UserID,LoginName from tb_User where OrganizationID=" + departmentValue + "";
string TheReturnValue = null; //返回值
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataAdapter adapter = null;
using (conn = new SqlConnection("---------連接字符串--------"))
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
if (conn.State == ConnectionState.Broken)
{
conn.Close();
conn.Open();
}
try
{
cmd = new SqlCommand(sql, conn);
adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
TheReturnValue += ds.Tables[0].Rows[i][0].ToString() +","+ ds.Tables[0].Rows[i][1].ToString();
TheReturnValue += ",";
}
context.Response.Write(TheReturnValue);
}
catch (Exception ex)
{
throw ex;
}
}
}
else
{
context.Response.Write("false");
}
}
另一個處理頁:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string loginName = context.Request.Form["childDrop"];
context.Session["contractLoginName"] = loginName;
}
第三個項目:
兩個DropDownList,一個TextBox,根據兩個DropDownList選中的值,當在文本框中輸入數據時,可以顯示仿照百度式的搜索列表,當選中后文本庫的值后,按一下Enter,
本人技術有限,不能實現百度那樣的選中值后自動查找
DropDownList:區域
DropDownList:街道
TextBox:物業地址
HTML代碼:
<div>
<asp:DropDownList ID="dropqy" runat="server" DataValueField="DistrictID" DataTextField="name" onchange="RegionChange()">
</asp:DropDownList>
<asp:DropDownList ID="ddlCommunity" runat="server" DataValueField="CommunityID" DataTextField="CommunityName" onchange="handleCommunity()">
</asp:DropDownList>
<asp:TextBox ID="txtdz" runat="server" key="地址"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="搜索" style="display:none"/>
</div>
js腳本:
<link href="http://www.cnblogs.com/Styles/jquery.ui.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="http://www.cnblogs.com/Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/jquery-ui-1.8.22.custom.js" type="text/javascript"></script>
$(function () {
var d = "<%=txtdz.ClientID %>";
var RegionName = "<%=dropqy.ClientID %>";
var CommunityName = "<%=ddlCommunity.ClientID %>";
$("#" + d).autocomplete({
source: function (request, response) {
$.ajax({
url: "http://www.cnblogs.com/Pages/SearchHouseInfoForAcceptPage.ashx?keyword=" + encodeURIComponent(request.term) + "&&parentDrop=" + encodeURIComponent($('#' + RegionName).val()) + "&&childDrop=" + encodeURIComponent($('#' + CommunityName).val()) + "",
data: {
name: request.term
},
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return { value: item };
}));
}
});
}
});
});
function document.onkeydown() {
var btn = "<%=Button1.ClientID %>";
var button = document.getElementById(btn);
if (event.keyCode == 13) {
button.click();
event.returnValue = false;
}
}
后台代碼:
在Page_Load中
//定義文本框的事件,當觸發文本框的事件時,觸發按鈕的事件
this.txtdz.Attributes["onkeypress"] = "if(event.keyCode==13){" + this.Button1.ClientID + ".click();return false;}";
使用委托:
//獲取選中的物業地址,傳給父頁面
public class UserControlEventTest : EventArgs
{
public string _address;
public UserControlEventTest(string address)
{
this._address = address;
}
}
public delegate void SubmitUserHandler(object sender, UserControlEventTest e);
public event SubmitUserHandler SubmitUserEvent;
protected void Button1_Click(object sender, EventArgs e)
{
UserControlEventTest userControlEventTest = new UserControlEventTest(txtdz.Text);
SubmitUserEvent(this, userControlEventTest);
}
ashx處理頁面代碼:
string keyword = context.Request.QueryString["keyword"];
keyword = System.Web.HttpUtility.UrlDecode(keyword);
regionID = context.Request.QueryString["parentDrop"];
communityID = context.Request.QueryString["childDrop"];