经过一个多星期的研究,各种查找资料终于自己实现了Jquery Ajax Json ashx 的前后台数据交流功能
首先一点,Ajax只能对应一个ashx文件,多余两个,如果打开异步传输的async: true,第二个无法返回数据。
第二post和get的方式除了w3shcool中说的HTTP 方法:GET 对比 POST,在后台的代码上也有一定的区分
使用Jquery封装的Ajax比较简单,Json需要解析。
1.新建类Jsonconvert.cs,用于Json的解析和转换
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Json;usingSystem.ServiceModel.Web;using System.IO;//MemoryStream
using System.Text;//StringBuilder
///
///Json 的摘要说明///
public static classJsonconn
{public static string ToJsJson(this objectitem) {
DataContractJsonSerializer serializer= newDataContractJsonSerializer(item.GetType());using (MemoryStream ms = newMemoryStream()) {
serializer.WriteObject(ms, item);
StringBuilder sb= newStringBuilder();
sb.Append(Encoding.UTF8.GetString(ms.ToArray()));returnsb.ToString();
}
}///
///Json反序列化,用于接收客户端Json后生成对应的对象///
public static T FromJsonTo(this stringjsonString) {
DataContractJsonSerializer ser= new DataContractJsonSerializer(typeof(T));
MemoryStream ms= newMemoryStream(Encoding.UTF8.GetBytes(jsonString));
T jsonObject=(T)ser.ReadObject(ms);
ms.Close();returnjsonObject;
}
}
View Code
2.新建类用于保存属性
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;///
///data 的摘要说明///
public classdata
{publicdata()
{//
//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中的写法:
usingSystem;usingSystem.Web;usingSystem.Collections.Generic;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Runtime.Serialization;usingSystem.Runtime.Serialization.Json;usingSystem.ServiceModel.Web;using System.IO;//MemoryStream
using System.Text;//StringBuilder
///
///建立新用户///
public classRegisterlastchk : IHttpHandler {///
///先检查名称,建立新用户///
///
public voidProcessRequest (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=newdata();var manager = newRegisterck();if (string.IsNullOrEmpty(name)) {throw new Exception("Username is empty");
}if(manager.Checkname(name)) {
NewUser signnew= newNewUser();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(stringname, HttpContext context) {
context.Response.ContentType= "text/plain";
context.Response.Charset= "utf-8";if (context.Request[name] == null) { return null; }string temp =context.Request[name];returntemp;
}///
///Json序列化,用于发送到客户端///
public boolIsReusable {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";