经过一个多星期的研究,各种查找资料终于自己实现了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; }
}

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) ;
}

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 == "") {
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 = "";//注册完成
context.Response.Write(reajax.ToJsJson());
}
else {
reajax.d = ""; //注册失败
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;
}
} }

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

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

Jquery Ajax Json ashx 实现前后台数据传输的更多相关文章

  1. 基于Jquery+Ajax+Json+存储过程 高效分页

    在做后台开发中,都会有大量的列表展示,下面给大家给大家分享一套基于Jquery+Ajax+Json+存储过程高效分页列表,只需要传递几个参数即可.当然代码也有改进的地方,如果大家有更好的方法,愿留下宝 ...

  2. 练习 jquery+Ajax+Json 绑定数据 分类: asp.net 练习 jquery+Ajax+Json 绑定数据 分类: asp.net

    练习 jquery+Ajax+Json 绑定数据

  3. Jquery+ajax+json+servlet原理和Demo

    Jquery+ajax+json+servlet原理和Demo 大致过程: 用户时间点击,触发js,设置$.ajax,开始请求.服务器响应,获取ajax传递的值,然后处理.以JSON格式返回给ajax ...

  4. php+jquery+ajax+json简单小例子

    直接贴代码: <html> <title>php+jquery+ajax+json简单小例子</title> <?php header("Conte ...

  5. 如何构建ASP.NET MVC4&JQuery&AJax&JSon示例

    背景: 博客中将构建一个小示例,用于演示在ASP.NET MVC4项目中,如何使用JQuery Ajax. 步骤: 1,添加控制器(HomeController)和动作方法(Index),并为Inde ...

  6. asp.net中利用Jquery+Ajax+Json实现无刷新分页(二)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PageTest.aspx.cs ...

  7. ajax+json+ashx实现一个页面多个tab的分页

    1:项目功能需求:我的荣誉.审核中的荣誉.审核通过的荣誉在一个页面分别作列表展示.每个tab都需要分页,对实现的功能做个简单总结. 2:前台页面:引用的DBPage.js和pageCss.css实现分 ...

  8. Jquery ajax json 不执行success的原因 坑爹

    最近在看jQuery的API文档,在使用到jQuery的ajax时,如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数,极度郁闷.后面改为1.2.6版本可 ...

  9. 玩转Web之Json(二)----jquery easy ui + Ajax +Json+SQL实现前后台数据交互

    最近在学Json,在网上也找过一些资料,觉得有点乱,在这里,我以easy ui的登录界面为例来说一下怎样用Json实现前后台的数据交互 使用Json,首先需要导入一些jar包,这些资源可以在网上下载到 ...

随机推荐

  1. oracle 数据库 基础操作

    一.oracle基本常用的数据类型 varchar(长度) 字符串 char(长度) 字符 number(x,y) x表示总位数 y表示保留小数点后几位数 eg面试题:number(5,3)最大的数是 ...

  2. LeetCode——Anagrams

    Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be ...

  3. 预装WIN8改装WIN7之BIOS设置

    不少预装WIN8/10的朋友觉得WIN8/10不好用,想改装WIN7,可改装之后常常出现各种问题,甚至不能启动,往往是BIOS设置不当. 本文以联想小新V2000 预装WIN8.1中文版为例,说说WI ...

  4. LVM详解笔记pv-vg-lv创建和扩展

    LVM Logical Volume Manager(逻辑卷管理) 是Linux环境下对底层磁盘的一种管理机制(方式),处在物理磁盘和文件系统之间. 名词: PV (Physical Volume)物 ...

  5. Redis之持久化和主从同步

    Redis作为内存数据库,所有数据都保存在内存中, 一旦程序停止工作, 数据都将丢失. 需要我们重新从其他地方加载数据. 不过Redis提供了两种方式保存Redis中的数据一种是dump内存直接存入r ...

  6. 189. Rotate Array【easy】

    189. Rotate Array[easy] Rotate an array of n elements to the right by k steps. For example, with n = ...

  7. HTML5 中fullscreen 中的几个API和fullscreen欺骗

    // 转自:https://my.oschina.net/jackyrong/blog/114086   HTML 5中的full screen,目前可以在除IE和opera外的浏览器中使用 ,有的时 ...

  8. DataUml Design 教程4-代码生成

            DataUml Design 生成代码非常灵活,它是基于模板形式生成代码,如果不懂类结构的话写模型就比较困难了.这里我只讲解下如何生成代码,代码模板规则下一节将介绍.        1 ...

  9. Hibernate使用注意事项

    映射的POJO类型中如果有基本类型最好都是用包装类来代替: 注意关联关系的正确设置,一对一(主键方式.外键外键方式),一对多和多对多的配置,单向.双向的配置: 更新核心配置文件的mapping:如果是 ...

  10. Yarn源码分析之MRAppMaster上MapReduce作业处理总流程(一)

    我们知道,如果想要在Yarn上运行MapReduce作业,仅需实现一个ApplicationMaster组件即可,而MRAppMaster正是MapReduce在Yarn上ApplicationMas ...