Ajax发送数据及接受数据(接口及json数据解析)
Ajax传输轻量数据(JSON数据格式)前台发送
function push() {
$.ajax({
url: "http://",//对方接受地址
data: {'data':'<%=ss%>'},//传输数据
type: "POST",//传输方式
datatype: "json",//数据格式
success: function (result) {//接受返回值,用于判断是否传输成功
var dataObj = eval("(" + result + ")");//解析返回值(这里我返回的是一个json数据){”errocode ”: “0”}
if (dataObj.errocode == 0)//分析返回数据
{
alert("推送成功!");
}
alert(result);
},
error: function (err, ex) {
alert("查询失败!");
}
});
}
后台传输数据JSON数据格式
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();//数据源
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://目标网址", ss);
JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
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+"条数据");
}
}
/// <summary>
/// 传输方法
/// </summary>
/// <param name="url">目标地址</param>
/// <param name="param">传输数据</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; }//一个唯一编号
public DateTime request_time { get; set; }//预定送花日期
public string name { get; set; }//姓名
public string mobile { get; set; }//手机
public string address { get; set; }//详细地址
public string express_no { set; get; }//物流单号
public string express_time { set; get; }//时间
public string express_name { set; get; }//物流公司名称
public int num { get; set; }//数量
}
public class PushCard_no {
public string card_no { get; set; }//订单号
}
/// <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();
//这里使用自定义日期格式,如果不使用的话,默认是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;
}
}
后台接受json数据并解析入库(后台接受并解析)
<%@ 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";//服务端需要返回一段普通文本给客户端
context.Response.AddHeader("Access-Control-Allow-Origin","*");//跨域请求
Entities db = new Entities();//实体声明
if (!string.IsNullOrEmpty(context.Request.Form["card_no"]))//获取请求参数
{
string json = context.Request.Form["card_no"].ToString();
// string tt = context.Request.Form["reciever"].ToString();
JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类
OrderData list = js.Deserialize<OrderData>(json); //将json数据转化为对象类型并赋值给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数据
{
S_实体AnotherOrder = new 实体();
AnotherOrder.OCodeNum = _card_Password;//卡号密码
AnotherOrder.Order_no = order_no;//外来订单号
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;//总数
AnotherOrder.OPeople = send_name;//送花人姓名
AnotherOrder.Otel = send_mobile;//送花人电话
AnotherOrder.blessing_message = message;//祝福语
AnotherOrder.blessing_tpl = tpl;//祝福卡样式地址
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());//预定送花日期
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;//外来订单(标记为1)
AnotherOrder.OState = "0";//已下单
AnotherOrder.OCreatTime = DateTime.Now;
db.S_实体.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>
/// 构造对象
/// </summary>
public struct OrderData {
public string card_no { get; set; }//鲜花卡编号,为空则表示没有使用鲜花卡
public string order_no { get; set; }//订单编号
public int pay_type { get; set; }//支付方式,1:鲜花卡,2:微信支付
public int pay_status { get; set; }//支付状态,0:未会付,1:已支付
public decimal total_amount { get; set; }//总金额
public int total_num { get; set; }//商品总件数
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; }//送花人手机号,如果为空则为匿名
}
public class blessing//祝福
{
public string message { get; set; }//祝福语
public string tpl { get; set; }//祝福卡样式地址
}
public class reciever//收花人信息,可能存在多个
{
public int id { get; set; }//一个唯一编号
public DateTime request_time { get; set; }//预定送花日期
public string name { get; set; }//姓名
public string mobile { get; set; }//手机
public string address { get; set; }//详细地址
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();
//这里使用自定义日期格式,如果不使用的话,默认是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\\":\\"错误提示信息\\"" + "}";
}
else if(Tag==4)
{
xxx = "{\\"errcode\\":\\"2\\",\\"errmsg\\":\\"错误提示信息\\"" + "}";
}
else if(Tag==5)
{
xxx = "{\\"errcode\\":\\"3\\",\\"errmsg\\":\\"错误提示信息错误提示信息\\"" + "}";
}
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;
}
}
}
文中用到的数据JSON数据格式(组合式数据类型)
"{ 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数据亦可用这样的方式组成(根据自己的需求,灵活运用),再进行传输。
Ajax和JSON数据的解析,日常中是常用到的,本人一个入门的程序员,不对之处能给与改正。