.net Ajax与后台一般处理程序(ashx) 交互

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/swjian1997/article/details/82027046

    本文主要实现无动态刷新查询后台数据功能,主要用到ajax+ashx+sqlserver进行交互.

首先需要引用Jquery:

 <script language="javascript" type="text/javascript" src="../js/jquery.js">

html脚本:

<asp:TextBox ID="tb_corpName" runat="server" MaxLength="100" Width="369px"></asp:TextBox>

前台通过一个事件来调用ashx:

<script type="text/javascript">
    $(function () {
        $("#tb_corpName").blur(function () {           //鼠标失去焦点事件
            var corpName = $("#tb_corpName").val();     
            $.ajax({        
                type: "post",                           //提交方式     
                url: "/ashx/FZGpyShowData.ashx",        //一般处理程序的路径
                data: { corpName: corpName },           //向后台传入的值
                dataType: "json",                       //返回值格式
                success: function (data) {              //返回成功后将要做的事,这里是返回一个表
                    $("#tb_CreditCode").val(data[0].CreditCode);    
                    $("#tb_corpCode").val(data[0].CorpCode);
                    $("#tb_linkTel").val(data[0].LinkPhone);

                    $("#corpProvince option[text='" + data[0].StateName + "']").attr("selected", true);
                    showCity();
                    $("#corpCity option[text='" + data[0].AdminAreaName + "']").attr("selected", true); 

                    $("#tb_address").val(data[0].Address);
                    $("#tb_linkMan").val(data[0].LinkMan);
                    $("#tb_Mobile").val(data[0].LinkMobile);
                }
            });
        })
    })
</script>

后台来接收前台传过来的值,对其进行操作:

     public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string corpName = context.Request["corpName"].Trim().ToString();      //接收前台传过来的参数
            if (corpName != "")
            {
                string sql = @"select top 1 CorpName,CreditCode,CorpCode,LinkPhone,StateName,AdminAreaName,LinkMan,LinkMobile,Address from tbProductOrder as a 
                                        inner join tbStateDic as b on a.StateNum = b.StateNum
                                        inner join tbAdminAreaClass on a.CityNum = AdminAreaClassID
                                        where CorpName =@CorpName order by CorpName";
                SqlParameter[] par = new SqlParameter[1];
                par[0] = new SqlParameter("@CorpName", corpName);
                DataSet ds = DBHerpler.Load(sql, par); 
                string json = SerializerHelper.ToJsonString(ds.Tables[0]);    //返回json类型的数据
                context.Response.Write(json);                      
                context.Response.End(); 
            } 
        }

SerializerHelper类的定义:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json;

/// <summary>
/// SerializerHelper 的摘要说明
/// </summary>
public static class SerializerHelper
{
    /// <summary>
    /// 反序列化XML文件
    /// </summary>
    public static T LoadFromXmlFile<T>(string filepath) where T : class
    {
        using (FileStream stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stream);
        }
    }

    /// <summary>
    /// 反序列化XML字符串
    /// </summary>
    public static T LoadFromXmlString<T>(string xml) where T : class
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        byte[] bytes = Encoding.UTF8.GetBytes(xml);

        using (MemoryStream stream = new MemoryStream(bytes))
        {
            return (T)serializer.Deserialize(stream);
        }
    }

    /// <summary>
    /// 序列化XML对象
    /// </summary>
    public static string SaveToXmlString<T>(T entity) where T : class
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(stream, entity);
            return Encoding.UTF8.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// 序列化Json对象
    /// </summary>
    public static string ToJsonString(object obj)
    {
        return ToJsonString<object>(obj);
    }

    /// <summary>
    /// 序列化Json对象
    /// </summary>
    public static string ToJsonString<T>(T obj) where T : class
    {
        string text = JsonConvert.SerializeObject(obj);
        return text;
    }

    /// <summary>
    /// 反序列化Json字符串
    /// </summary>
    public static T ToJsonObject<T>(string text) where T : class
    {
        T obj = (T)JsonConvert.DeserializeObject(text, typeof(T));
        return obj;
    }
}

 

如果向后台传入多个参数在data里面用逗号分割可写多个参数:

    data: { corpName: corpName , corpName2: corpName2} 

展开阅读全文
博主设置当前文章不允许评论。

ajax后台交互的问题

07-07

[color=#FF0000]数据库返回的数据,不使用F5刷新,不在页面显示出来,怎么办?[/color]rn代码太多了,我只复制一部分,重要的,下面的是使用UI插件,写的,点击按钮,数据就提交到后台了,这个步骤是正常的rn[code=javascript]rn$('#question').dialog(rn autoOpen:false,rn modal:true,rn resizable:false,rn width:500,rn height:360,rn buttons:rn '发布':function()rn //发表提问rn $(this).ajaxSubmit(rn url:'php/add_content.php',rn type:'POST',rn data:rn user:$.cookie('user'),rn content : $('.uEditorIframe').contents().find('#iframeBody').html(),rn ,rn beforeSubmit:function(formDate,jqForm,options)rn $('#loading').dialog('open');rn $('#question').dialog('widget').find('button').eq(1).button('disable');rn ,rn success:function(responseText,statusText)rn if(responseText)rn $('#question').dialog('widget').find('button').eq(1).button('enable');rn $('#loading').css('background', 'url(img/success.gif) no-repeat 20px center').html('提问成功...');rn //window.location.reload();rn setTimeout(function()rn $('#loading').dialog('close');rn $('#question').dialog('close');rn $('#question').resetForm();rn $('#loading').css('background', 'url(img/loading.gif) no-repeat 20px center').html('提交问题中...');rn ,1000)rn rn ,rn )rn rn rn );rn//这里是为了页面展示后台的内容,使用的ajaxrn$.ajax(rn url : 'php/show_content.php',rn type : 'POST',rn success : function (response, status, xhr) rn //这里面忽视了很多代码rn rn)rn[/code]rn下面是两个PHP文件rn[code=php]rn//add的文件rnrn//show的文件rn $value ) rn $row[$key] = urlencode(str_replace("\n","", $value));rn rn $json .= urldecode(json_encode($row)).',';rn rn rn echo '['.substr($json, 0, strlen($json) - 1).']';rn rn mysql_close();rn?>rn//config文件rnrn[/code]rn[color=#FF0000]数据库肯定没问题的,我想问下,怎么修改PHP文件或JS文件,能实现,提交数据后,立马在页面显示出来,且不使用F5或其他方法对整个页面刷新。[/color] 论坛

没有更多推荐了,返回首页