zoukankan      html  css  js  c++  java
  • 【转】JQuery以JSON方式提交数据到服务端

    JQuery将Ajax数据请求进行了封装,从而使得该操作实现起来容易许多。以往我们要写很多的代码来实现该功能,现在只需要调用$.ajax()方法,并指明请求的方式、地址、数据类型,以及回调方法等。下面的代码演示了如何将客户端表单数据封装成JSON格式,然后通过JQuery的Ajax请求将数据发送到服务端,并最终将数据存储到数据库中。服务端定义为一个.ashx文件,事实上你可以将服务端定义为任何能接收并处理客户端数据的类型,如Web Service,ASP.NET Page,Handler等。

      首先,在客户端,通过JavaScript脚本将页面表单数据封装成JSON格式。GetJsonData()函数完成了这一功能。然后我们通过$.ajax()方法将数据发送到服务端的RequestData.ashx。其中用到了JSON.stringify()方法,它可以将客户端发送的数据转换成JSON对象,详细的内容可以看这里https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    $("#btnSend").click(function() {
    $("#request-process-patent").html("正在提交数据,请勿关闭当前窗口...");
    $.ajax({
    type: "POST",
    url: "RequestData.ashx",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(GetJsonData()),
    dataType: "json",
    success: function (message) {
    if (message > 0) {
    alert("请求已提交!我们会尽快与您取得联系");
    }
    },
    error: function (message) {
    $("#request-process-patent").html("提交数据失败!");
    }
    });
    });

    function GetJsonData() {
    var json = {
    "classid": 2,
    "name": $("#tb_name").val(),
    "zlclass": "测试类型1,测试类型2,测试类型3",
    "pname": $("#tb_contact_people").val(),
    "tel": $("#tb_contact_phone").val()
    };
    return json;
    }

    再来看看服务端的代码,RequestData.ashx.

    [Serializable]
    public class RequestDataJSON
    {
    public int classid { get; set; }
    public string name { get; set; }
    public string zlclass { get; set; }
    public string pname { get; set; }
    public string tel { get; set; }
    }

    /// <summary>
    /// Summary description for RequestData
    /// </summary>
    public class RequestData : IHttpHandler
    {
    public void ProcessRequest(HttpContext context)
    {

    context.Response.ContentType = "application/json";
    var data = context.Request;
    var sr = new StreamReader(data.InputStream);
    var stream = sr.ReadToEnd();
    var javaScriptSerializer = new JavaScriptSerializer();
    //将提交的数据封装到实体对象StudentEntity里
    var PostedData = javaScriptSerializer.Deserialize<StudentEntity>(stream);


    int sid= PostedData.sid;
    string name = PostedData.sname;

    context.Response.ContentType = "text/plain";

    }

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

  • 相关阅读:
    关于firstChild,firstElementChild和children
    trim(),正则表达式中文匹配
    Shell之基本用法
    Samba服务部署
    Linux基础(3)
    linux基础(2)
    Linux基础(1)
    网络基础及网络协议
    操作系统简介
    为何要学习计算机基础
  • 原文地址:https://www.cnblogs.com/xiaowei-blog/p/4404920.html
Copyright © 2011-2022 走看看