您的位置:首页 > Web前端 > JQuery

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

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

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

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

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

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

<%@ 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";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: