Jquery Ajax Json ashx 实现前后台数据传输

经过一个多星期的研究,各种查找资料终于自己实现了Jquery  Ajax Json ashx 的前后台数据交流功能

首先一点,Ajax只能对应一个ashx文件,多余两个,如果打开异步传输的async: true,第二个无法返回数据。

第二post和get的方式除了w3shcool中说的HTTP 方法:GET 对比 POST,在后台的代码上也有一定的区分

使用Jquery封装的Ajax比较简单,Json需要解析。

1.新建类Jsonconvert.cs,用于Json的解析和转换

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.IO;//MemoryStream
using System.Text;//StringBuilder

/// <summary>
/// Json 的摘要说明
/// </summary>
public static class Jsonconn
{
    

    public static string ToJsJson(this object item) {

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(item.GetType());

        using (MemoryStream ms = new MemoryStream()) {

            serializer.WriteObject(ms, item);

            StringBuilder sb = new StringBuilder();

            sb.Append(Encoding.UTF8.GetString(ms.ToArray()));

            return sb.ToString();

        }

    }

    /// <summary>
    /// Json反序列化,用于接收客户端Json后生成对应的对象
    /// </summary>
    public static T FromJsonTo<T>(this string jsonString) {

        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));

        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));

        T jsonObject = (T)ser.ReadObject(ms);

        ms.Close();

        return jsonObject;

    }
}
View Code

2.新建类用于保存属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// data 的摘要说明
/// </summary>
public class data
{
    public data()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    public string d { get; set; }
}

3.前台Ajax的写法

  
        $.ajax({
            url: 'Ashx/Registerlastchk.ashx',
            type: 'post',
           // contentType: "application/json; charset=utf-8",
            data: {username:$("#Username").val(),password: $("#Password").val(),email:$("#signup_email").val(),pass:1} ,
            datatype: "json",
            async: true,          
            beforeSend: function () {
                $("#div_signing").show();
                $('#SignUpButton').attr('disabled', "true"); //添加disabled属性                
            },
            error:function(data){
                $("#div_signing_info").html("连接服务器失败");
            },
            success: function (data) {
              
                var datastring = JSON.parse(data);//******很多代码都丢了这段
            
           alter(datastring.d) ;
                }
               
View Code

4.ashx中的写法:

<%@ WebHandler Language="C#" Class="Registerlastchk" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.IO;//MemoryStream
using System.Text;//StringBuilder
/// <summary>
/// 建立新用户
/// </summary>
public class Registerlastchk : IHttpHandler {
    /// <summary>
    /// 先检查名称,建立新用户
    /// </summary>
    /// <param name="context"></param>
    public void ProcessRequest (HttpContext context) {
        string pass = GetJsonClient("pass", context);
        if (pass == "1") {
            string password = GetJsonClient("password", context);
            string email = GetJsonClient("email", context);
            string name = GetJsonClient("username", context);
            data reajax=new data();            
            var manager = new Registerck();
            if (string.IsNullOrEmpty(name)) {
                throw new Exception("Username is empty");

            }
            if (manager.Checkname(name)) {
                NewUser signnew = new NewUser();
                var result = signnew.signnewuser(name, password, email);
                if (result) {
                    reajax.d = "1";//注册完成
                    context.Response.Write(reajax.ToJsJson());
                }
                else {
                    reajax.d = "0"; //注册失败
                    context.Response.Write(reajax.ToJsJson());               
                }            
               
            }
            else {
                reajax.d = "-1"; //用户名存在
                context.Response.Write(reajax.ToJsJson()); 
            
            }

        }
    }
    public string GetJsonClient(string name, HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";
        if (context.Request[name] == null) { return null; }
        string temp = context.Request[name];
        return temp;

    }
    /// <summary>
    /// Json序列化,用于发送到客户端
    /// </summary>


 
    public bool IsReusable {
        get {
            return true;
        }
    }

}
View Code

post的时候原来是datatype是Json,ContentType 最好为"text/plain",试过“Aplication/Json”无获得数据,但是get方式时候可以货到,Post时候为null,原因不明,应该使用方法中 T FromJsonTo,也是极好的,还未做实验,今天太晚了,明天试试

        context.Response.ContentType = "text/plain";
        context.Response.Charset = "utf-8";

 

posted @ 2013-11-29 00:39  KeithMorning  阅读(2447)  评论(0编辑  收藏  举报