Asp.Net 使用jquery json,注意后台返回的内容。

后台代码

 /// <summary>
    /// CommonHandler 的摘要说明
    /// </summary>
    public class CommonHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.Expires = -1;
            context.Response.ContentType = "text/plain";
            if (string.Equals((context.Request["ajaxmethod"] ?? ""), "getroom", StringComparison.OrdinalIgnoreCase))
            {
                RoomSelect(context);
            }
            context.Response.End();
        }

        public void RoomSelect(HttpContext context)
        {
            HttpRequest request = context.Request;
            HttpResponse response = context.Response;
            string val = (request["val"] ?? "").Trim();
            var list = BusinessRoom_DAL.BusinessRoomList.Where(p => p.RoomRegion == val);
            StringBuilder jsonBuilder = new StringBuilder("{\"id\":\"\",\"val\":\"全部\"},");
            foreach (BusinessRoom model in list)
            {
                jsonBuilder.AppendFormat("{{\"id\":\"{0}\",\"val\":\"{1}\"}},", model.ID, model.Room.Replace("\"", ""));
            }
            string json = "[" + jsonBuilder.ToString().TrimEnd(',') + "]";
            response.Write(json);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

前台:

function changeSelect(obj, ddlRoomId) {
        obj = $(obj);
        var val = obj.val();
        obj.next('img').show();
        if (val != "") {
            $.ajax({
                type: "Get",
                url: '<%=ResolveUrl("~/Ashx/CommonHandler.ashx") %>',
                data: 'ajaxmethod=getroom&val=' + escape(val),
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        //eval("(" + ret + ")")
                        alert(data[0].demoData);
                    }
                    obj.next('img').hide();
                },
                complete: function () {
                    obj.next('img').hide();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // 通常 textStatus 和 errorThrown 之中
                    // 只有一个会包含信息
                    // 调用本次AJAX请求时传递的options参数
                }
            });
        }
    }

posted on 2012-04-27 15:45  jianshaohui  阅读(136)  评论(0编辑  收藏  举报

导航