IT技術(shù)

Ajax發(fā)送數(shù)據(jù)及接受數(shù)據(jù)(接口及json數(shù)據(jù)解析)
作者:
來源: 本站
發(fā)布日期: 2018/2/12 19:00:20
點(diǎn)擊量: 4308次
【 字體:
背景顏色:

             Ajax發(fā)送數(shù)據(jù)及接受數(shù)據(jù)(接口及json數(shù)據(jù)解析)

   Ajax傳輸輕量數(shù)據(jù)(JSON數(shù)據(jù)格式)前臺(tái)發(fā)送

      function push() {

            $.ajax({

                url: "http://",//對方接受地址

                data: {'data':'<%=ss%>'},//傳輸數(shù)據(jù)

                type: "POST",//傳輸方式

                datatype: "json",//數(shù)據(jù)格式

                success: function (result) {//接受返回值,用于判斷是否傳輸成功

                    var dataObj = eval("(" + result + ")");//解析返回值(這里我返回的是一個(gè)json數(shù)據(jù))errocode ”: “0”}

                    if (dataObj.errocode == 0)//分析返回?cái)?shù)據(jù)

                    {

                        alert("推送成功!");

                    }

                    alert(result);

                   

                },

                error: function (err, ex) {

                    alert("查詢失敗!");

                }

            });

        }

 

后臺(tái)傳輸數(shù)據(jù)JSON數(shù)據(jù)格式

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using Models;

using System.Collections.Generic;

using Newtonsoft.Json.Converters;

using Newtonsoft.Json;

using System.Web.Script.Serialization;

using System.Net;

using System.IO;

using System.Text;

 

public partial class TEst_PushTest : System.Web.UI.Page

{

    public string ss;

    public string order_no;

    public int a = 0;

 

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

 

 

 

    /// <summary>

    /// 推送按鈕

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void btnPush_Click(object sender, EventArgs e)

    {

      

            Entities db = new Entities();

        var orderInfo = db..Where(p => p.Order_another_tag == 1).OrderBy(p => p.OrderID).ToList();//數(shù)據(jù)源   

        List<reciever> recieverList = new List<reciever>();

        List<PushCard_no> cardnoList = new List<PushCard_no>();

        int b = 0;

        if(orderInfo!=null)

        {

            for(int i=0;i<orderInfo.Count();i++)

            {

                reciever Re = new reciever();

                Re.id = Convert.ToInt32(orderInfo[i].reciever_id);

                Re.request_time = Convert.ToDateTime(orderInfo[i].OFHTime);

                Re.name = getReciever(orderInfo[i].OAddress,0);

                Re.mobile = getReciever(orderInfo[i].OAddress,1);

                Re.address = getReciever(orderInfo[i].OAddress,2);

                Re.express_no = orderInfo[i].OLogisticsNum;

                Re.express_name = "";

                Re.num = 1;

               b++;

                ss = JsonSerialize(Re, 0, orderInfo[i].Order_no.ToString());

                string aa = PostMoths("http://目標(biāo)網(wǎng)址", ss);

 

                JavaScriptSerializer js = new JavaScriptSerializer();   //實(shí)例化一個(gè)能夠序列化數(shù)據(jù)的類

                returnData list = js.Deserialize<returnData>(aa);

                string errcode = list.errcode;

                if (errcode == "0")

                {

                    orderInfo[i].push_tag = 1;

                    a++;

                }

                else

                {

                    orderInfo[i].push_tag = Convert.ToInt32(errcode);

                }

            }

            db.SaveChanges();

            Response.Write("成功了:"+a+"條數(shù)據(jù)");        

        }       

    }

 

    /// <summary>

    /// 傳輸方法

    /// </summary>

    /// <param name="url">目標(biāo)地址</param>

    /// <param name="param">傳輸數(shù)據(jù)</param>

    /// <returns></returns>

    public static string PostMoths(string url, string param)

    {

        string strURL = url;

        System.Net.HttpWebRequest request;

        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);

        request.Method = "POST";

        request.ContentType = "application/json;charset=UTF-8";

        string paraUrlCoded = param;

        byte[] payload;

        payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);

        request.ContentLength = payload.Length;

        Stream writer = request.GetRequestStream();

        writer.Write(payload, 0, payload.Length);

        writer.Close();

        System.Net.HttpWebResponse response;

        response = (System.Net.HttpWebResponse)request.GetResponse();

        System.IO.Stream s;

        s = response.GetResponseStream();

        string StrDate = "";

        string strValue = "";

        StreamReader Reader = new StreamReader(s, Encoding.UTF8);

        while ((StrDate = Reader.ReadLine()) != null)

        {

            strValue += StrDate + "\\r\\n";

        }

        return strValue;

    }

 

 

    public class returnData

    {

        public string errcode { get; set; }

    }

 

    public class reciever

    {

        public int id { get; set; }//一個(gè)唯一編號(hào)

        public DateTime request_time { get; set; }//預(yù)定送花日期

        public string name { get; set; }//姓名

        public string mobile { get; set; }//手機(jī)

        public string address { get; set; }//詳細(xì)地址

        public string express_no { set; get; }//物流單號(hào)

        public string express_time { set; get; }//時(shí)間

        public string express_name { set; get; }//物流公司名稱

        public int num { get; set; }//數(shù)量      

     

    }

 

    public class PushCard_no {

        public string card_no { get; set; }//訂單號(hào)

    }

 

    /// <summary>

    /// 獲取收花人信息

    /// </summary>

    /// <param name="info">信息</param>

    /// <param name="tag">0為人名;1為電話;2為地址</param>

    /// <returns></returns>

    public string getReciever(object info,int tag)

    {

        string resulr = "";

        if (info != null)

        {

            string xxx = info.ToString();

            string[] userInfo = xxx.Split(' ');

            if (userInfo.Length >= 3)

            {

                if (tag == 0)

                {

                    resulr = userInfo[1];

                }

                else if (tag == 1)

                {

                    resulr = userInfo[2];

                }

                else if (tag == 2)

                {

                    resulr = userInfo[0];

                }

            }

        }

        return resulr;

    }

 

 

    public string JsonSerialize(object obj, int Tag,string  order_no)

    {

        IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();

        //這里使用自定義日期格式,如果不使用的話,默認(rèn)是ISO8601格式  

        timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

        string xxx = "";     

        if (Tag == 0)

        {

            xxx = "{\\"order_no\\":\\""+ order_no + "\\",\\"reciever\\":" + JsonConvert.SerializeObject(obj, timeConverter) + "}";

            //return xxx;

        }

        return xxx;

    }

}

 

 

 

后臺(tái)接受json數(shù)據(jù)并解析入庫(后臺(tái)接受并解析)

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

 

using System;

using System.Web;

using Models;

using System.Linq;

using Newtonsoft.Json.Converters;

using Newtonsoft.Json;

using System.Web.Script.Serialization;

using System.Collections.Generic;

 

public class OrderInfo : IHttpHandler {

 

    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/plain";//服務(wù)端需要返回一段普通文本給客戶端

        context.Response.AddHeader("Access-Control-Allow-Origin","*");//跨域請求

        Entities db = new Entities();//實(shí)體聲明

        if (!string.IsNullOrEmpty(context.Request.Form["card_no"]))//獲取請求參數(shù)

        {

            string json = context.Request.Form["card_no"].ToString();

            // string tt = context.Request.Form["reciever"].ToString();

            JavaScriptSerializer js = new JavaScriptSerializer();   //實(shí)例化一個(gè)能夠序列化數(shù)據(jù)的類

            OrderData list = js.Deserialize<OrderData>(json);    //將json數(shù)據(jù)轉(zhuǎn)化為對象類型并賦值給list

            string card_no = list.card_no;

            string order_no = list.order_no;            

            int pay_type = list.pay_type;

            int pay_status = list.pay_status;

            decimal total_amount = list.total_amount;

            int total_num = list.total_num;

            string send_name = list.send_people.send_name;

            string send_mobile = list.send_people.send_mobile;

            string message = list.blessing.message;

            string tpl = list.blessing.tpl;

            string _card_Password = "";

            if (!string.IsNullOrEmpty(card_no))

            {

              

                var card = db.S_Code.SingleOrDefault(p=>p.CodeGUID == card_no);

                if (card != null)

                {

                    _card_Password = card.CodeGUID;

 

                }

                else

                {

                    context.Response.Write(JsonSerialize(4));

                    return;

                }

            }

 

            List<reciever> recieverList = list.reciever;

            List<info> infoList = list.info;

            int AllCount = 0;

            if (recieverList.Count >0  && infoList.Count()>0)

            {

                for (int i = 0; i < recieverList.Count(); i++)//遍歷list數(shù)據(jù)

                {

                    S_實(shí)體AnotherOrder = new 實(shí)體();

                    AnotherOrder.OCodeNum = _card_Password;//卡號(hào)密碼

                    AnotherOrder.Order_no = order_no;//外來訂單號(hào)

                    AnotherOrder.OType = getPay_type(pay_type);//支付方式

                    AnotherOrder.pay_status = getpay_status(pay_status);//是否支付

                    AnotherOrder.SPrice = (Int32)Math.Round(total_amount,0);//總額

                    AnotherOrder.OCount = total_num;//總數(shù)

                    AnotherOrder.OPeople = send_name;//送花人姓名

                    AnotherOrder.Otel = send_mobile;//送花人電話

                    AnotherOrder.blessing_message = message;//祝福語

                    AnotherOrder.blessing_tpl = tpl;//祝??邮降刂?/span>

                    AnotherOrder.OAddress = recieverList[i].address + " " + recieverList[i].name + " " + recieverList[i].mobile;//收件人信息

                    AnotherOrder.reciever_id = recieverList[i].id;

                    AnotherOrder.OFHTime =  Convert.ToDateTime(recieverList[i].request_time.ToString());//預(yù)定送花日期

                    if (!string.IsNullOrEmpty(recieverList[i].batch))//批次  為空保存為1

                    {

                        AnotherOrder.reciever_batch = Convert.ToInt32(recieverList[i].batch);

                    }

                    else

                    {

                        AnotherOrder.reciever_batch = 1;

                    }

                    AnotherOrder.info_unique_id = infoList[0].unique_id;//商品信息  

                    AnotherOrder.SPName = getProName(infoList[0].unique_id);

                    AnotherOrder.info_num = infoList[0].num;

                    AnotherOrder.info_amount = infoList[0].amount;

                    AnotherOrder.Order_another_tag = 1;//外來訂單(標(biāo)記為1)

                    AnotherOrder.OState = "0";//已下單

                    AnotherOrder.OCreatTime = DateTime.Now;

                    db.S_實(shí)體.Add(AnotherOrder);

                    db.SaveChanges();

                    AllCount++;

                }

                context.Response.Write(JsonSerialize(0));

            }           

        }

 

    }

 

    /// <summary>

    /// 存入商品名

    /// </summary>

    /// <param name="PId"></param>

    /// <returns></returns>

    public string getProName(int PId)

    {

        string result = "";

        Entities db = new Entities();

        var  proInfo =db.S_shiti.SingleOrDefault(p => p.CodeCLassID == PId);

        if (proInfo != null)

        {

            result = proInfo.CCname;

        }

        return result;

    }

 

    /// <summary>

    /// 構(gòu)造對象

    /// </summary>

    public struct  OrderData {

        public string card_no { get; set; }//鮮花卡編號(hào),為空則表示沒有使用鮮花卡

        public string order_no { get; set; }//訂單編號(hào)

        public int  pay_type { get; set; }//支付方式,1:鮮花卡,2:微信支付

        public int pay_status { get; set; }//支付狀態(tài),0:未會(huì)付,1:已支付

        public decimal  total_amount { get; set; }//總金額

        public int total_num { get; set; }//商品總件數(shù)

        public send_people send_people;//送花人信息

 

        public blessing blessing;//祝福語

        public List<reciever> reciever;//收花人信息

        public List<info> info;//商品信息

    }

 

    public class send_people//送花人信息

    {

        public string send_name { get; set; }//送花人姓名

        public string send_mobile { get; set; }//送花人手機(jī)號(hào),如果為空則為匿名

    }

 

    public class blessing//祝福

    {

        public string message { get; set; }//祝福語

        public string tpl { get; set; }//祝福卡樣式地址

    }

 

    public class reciever//收花人信息,可能存在多個(gè)

    {

        public int id { get; set; }//一個(gè)唯一編號(hào)

        public DateTime request_time { get; set; }//預(yù)定送花日期

        public string name { get; set; }//姓名

        public string mobile { get; set; }//手機(jī)

        public string  address { get; set; }//詳細(xì)地址

        public string batch { get; set; }//批次

    }

 

    public class info//訂單商品詳情

    {

        public int unique_id { get; set; }

        public int num { get; set; }

        public decimal amount { get; set; }

    }

 

    /// <summary>

    /// 將對象序列化為JSON格式

    /// </summary>

    /// <param name="o">對象</param>

    /// <returns>json字符串</returns>

    public static string SerializeObject(object o)

    {

        string json = JsonConvert.SerializeObject(o);

        return json;

    }

 

    public string JsonSerialize(int Tag)

    {

        IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();

        //這里使用自定義日期格式,如果不使用的話,默認(rèn)是ISO8601格式  

        timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

        string xxx="";

        if (Tag == 0)

        {

            xxx = "{\\"errcode\\":\\"0\\",\\"errmsg\\":\\"OK\\"" + "}";

        }

        else if (Tag == 1)

        {

            xxx = "{\\"errcode\\":\\"1\\",\\"errmsg\\":\\"Error\\"" + "}";

        }

        else if(Tag==3)

        {

            xxx = "{\\"errcode\\":\\"-1\\",\\"errmsg\\":\\"錯(cuò)誤提示信息\\"" + "}";

        }

        else if(Tag==4)

        {

            xxx = "{\\"errcode\\":\\"2\\",\\"errmsg\\":\\"錯(cuò)誤提示信息\\"" + "}";

        }

        else if(Tag==5)

        {

            xxx = "{\\"errcode\\":\\"3\\",\\"errmsg\\":\\"錯(cuò)誤提示信息錯(cuò)誤提示信息\\"" + "}";

        }

        return xxx;

    }

 

    public string getPay_type(int a)

    {

        string result = "";

        if (a == 1)

        {

            result = "鮮花卡";

        }

        else if (a == 2)

        {

            result = "微信支付";

        }

        return result;

    }

    public bool IsReusable {

        get {

            return false;

        }

    }

}

 

  文中用到的數(shù)據(jù)JSON數(shù)據(jù)格式(組合式數(shù)據(jù)類型)

"{ card_no: '1000000001', 'order_no': '1000000001', 'pay_type': 1,'send_people': { 'send_name': '張賽', 'send_mobile': '12345678901', 'blessing': [ { 'message': '祝你生日', 'tpl': '12345678901' },{ 'message': '祝你生日', 'tpl': '12345678901' }], 'reciever': { 'id': 'name', 'mobile': '1234567', 'address': '蓮花街道', 'batch': '1'}";

本文提到傳輸組合式json數(shù)據(jù)亦可用這樣的方式組成(根據(jù)自己的需求,靈活運(yùn)用),再進(jìn)行傳輸。

AjaxJSON數(shù)據(jù)的解析,日常中是常用到的,本人一個(gè)入門的程序員,不對之處能給與改正。

掃一掃在手機(jī)打開當(dāng)前頁

Contact

聯(lián)系我們

告訴我們您想要的吧!我們?yōu)楫?dāng)?shù)乜蛻籼峁I(yè)、及時(shí)的服務(wù)
地址:云南省昆明市白云路368號(hào)
電話:400-871-8716 (工作時(shí)間:09:00-18:00(周一至周五))
何總:23592693
李總:53815112
亚洲日韩在线a在线观看,欧美激情 在线观看,97色伦图片97综合影院,成人AV天堂一二三在线观看,欧美色吧视频在线观看,国产l精品国产亚洲区,久久综合亚洲图片,99久久国产综合精品1,久久AⅤ无码AV高潮AV喷吹,亚洲综合无码一区二区三区不卡
久久99精品久久久久婷婷| 91三级在线观看| 微拍秒拍福利一区二区| 在线看片免费人成视频国产片| 亚洲国产成人A片在线观看| 亚洲爆乳www无码专区| 亚洲国产欧美国产综合久久| 精品国产一区二区三区AV?性色 | 国产精品亚洲欧美云霸高清| 高清国产亚洲欧洲AV综合一区| 久久精品免视看国产盗摄| 无遮无挡爽爽免费毛片| 久久91精品综合国产首页| 国产成人午夜福利在线观看视频| 无码人妻斩一区二区三区| 国产AV一区二区三区传媒| 午夜男人一级毛片免费| 亚洲午夜精品久久久久久人妖| 爆乳一区二区三区无码| 亚洲最新无码成av人| 国产强伦姧在线观看午夜| 国产韩国精品一区二区三区久久| 亚洲综合AV色婷婷国产野外| 精品亚洲AⅤ在线观看| 国产人成精品香港三级在线| 国产妇乱子伦视频免费| 久久综合精品国产二区无码| 性欧洲精品VIDEOS| 99pao在线视频成精品| 日韩人妻无码精品二专区| 老司机久久影院| 凹凸国产熟女精品视频| 婷婷成人亚洲综合五月天| AV制服丝袜白丝国产网站| 亚洲中文字幕精品一区二区三区 | 亚洲综合无码精品一区二区三区| 日韩欧美久久一区二区| 国产一区二区三区毛片| 免费av无码无在线观看| 欧美激情中文字幕在线观看| 夜色资源站国产www在线视频|