您的位置:首页 > 其它

用Ajax提交数据到ashx处理数据

2012-07-31 17:41 169 查看
闲来无事,把最近使用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"];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: