网页开发中的数据流总结

 

1 JQuery Ajax

比较常见的就是使用JQuery中的Ajax进行数据的传递了。今天在此总结一下。

同时要注意一定最好不要将$.ajax(...)放到了最外层,即放到了$(function () {...}中。

1.1 跨域的情况

也就是本网站的js脚本请求本网站的Webservice(.asmx)或一般处理文件(.ashx)。

前端

// 调用发送数据调用事件的函数
$(".project_item_lst").bind('click', GetTargetXMXX);
// ...


$(function () {

// ....
$.ajax({
    type: "POST", //Post传参
    url: XMXX_Server_URL+"/GetXMXX?jsoncallback?",//服务地址
    dataType: "jsonp",
    //contentType: "application/json;charset=utf-8",
    jsonp: 'jsoncallback',
    data: { "bsm": bsm_2 },//参数birthday
    success: function (result) { 
    // ...
    
    },
    error: function (e) {
    window.alert(e.status);
    }

// ....

}
View Code

服务端

/// <summary>
/// 项目列表左侧的操作服务
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
[System.Web.Script.Services.ScriptService]
public class XMXXOperate : System.Web.Services.WebService
{

    /// <summary>
    /// 获取项目详情的接口
    /// </summary>
    /// <param name="bsm">X2014121911854</param>
    /// <returns></returns>
    [WebMethod]
    public string GetXMXX(string bsm)
    {
        string jsonCallBackFunName;
        DataContractJsonSerializer json;
        string result = "";
        XMXX dataResult;
        OracleConnect oracleConect;


        oracleConect = new OracleConnect();
        dataResult = oracleConect.GetXMXXObject(bsm);

        // get jsoncallback
        HttpContext.Current.Response.ContentType = "application/json;charset=utf-8";
        jsonCallBackFunName = HttpContext.Current.Request.Params["jsoncallback"].ToString();


        json = new DataContractJsonSerializer(dataResult.GetType());
        using (MemoryStream stream = new MemoryStream())
        {
            json.WriteObject(stream, dataResult);
            result = Encoding.UTF8.GetString(stream.ToArray());
        }

        // return data
        result = jsonCallBackFunName + '(' + result + ')';

        HttpContext.Current.Response.Write(result); // 此时返回的结果为Array [ object, ...,object]
        HttpContext.Current.Response.End();


        return "ok";
    }    

}
View Code

 

同时别忘了引用这两个

using System.Runtime.Serialization.Json;
using System.Text;

以及在WebService的Web.config配置(是服务端,和Web服务一起):

Protocols声明网页Get/Post方式,务必要增加这个节点,在system.web节点内。

<system.web>
    <!-- 。。。其他节点 -->
    <webServices>
      <protocols>
        <add name="HttpPost"/>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
</system.web>
View Code

 

1.2 非跨域情况

非跨域情况下的数据流可为:

JS --> .ashx --> .asmx

JS --> .ashx

.ashx文件适合产生供浏览器处理的、不需要回发处理的数据格式,例如用于生成动态图片动态文本等内容。

前端

$(function ()
{
  
    // ...
    var URL_GetData = "../../Handler/GetData.ashx"; //发布到99服务器时:"../../ZJECMS_MainWeb/Handler/GetData.ashx"; // 调试时:"../../Handler/GetData.ashx"
    var RefreashDirs = function (bsm) {
        /// <summary>
        /// 请求,获取项目目录
        /// </summary>
        /// <param name="bsm" type="string">项目标识码</param>
        $.ajax({
            url: URL_GetData+'?Method=GetXMDIRS&bsm=' + bsm,
            async: false,
            type: 'POST',
            success: function (response) {
                
                // parse data and convert to the json object
          zNodes = eval(response)
          // ...



              // return zNodes; // cheeck this return
            },
            error: function (e) {
               // window.alert(e.status);
            }
        });
    }
    // ...


}
View Code

本站前端的.ashx

using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;

namespace Project.Handle
{
    /// <summary>
    /// GetData 的摘要说明
    /// </summary>
    public class GetData : IHttpHandler
    {
        private HttpRequest Request;
        private HttpResponse Response;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            // context.Response.Write("Hello World");
            // string uploadDir = Server.MapPath("~\\TempFile\\Upload");
            Request = context.Request;
            Response = context.Response;
            string method = Request["Method"].ToString();
            MethodInfo methodinfo = this.GetType().GetMethod(method);
            methodinfo.Invoke(this, null);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

     public void GetXMDIRS()
        {
            string bsm = Request["bsm"].ToString();
            //XMXXOperate_Local.XMXXOperateSoapClient tsvc = new XMXXOperate_Local.XMXXOperateSoapClient();
            XMXXOperate.XMXXOperateSoapClient tsvc = new XMXXOperate.XMXXOperateSoapClient();
            string strJson = tsvc.GetTragetXMGDWJ(bsm);
            Response.Write(strJson);
        }
    }
}    
View Code

 

非跨域情况下参考代码2

function login() { 
$.ajax({  
url: 'common/handler/Login.ashx',  
type: 'POST',  
data: { 'username': $("#txtUsername").val(), 'password': $("#txtPassword").val() },  
dataType: 'json',  
timeout: 50000,  
//contentType: 'application/json;charset=utf-8',  
success: function (response) { 
alert(response.message);  
},  
error: function (err) {  
alert("执行失败"); 
}  
});  
}  

 

public class Login : IHttpHandler {

    public void ProcessRequest (HttpContext context) 
{
        context.Response.ContentType = "application/json";  
        //GET方式获取传递的数据  
        //string username = context.Request.QueryString["username"];  
        //string password = context.Request.QueryString["password"];  
  
        //POST方式获取传递的数据  
        string username = context.Request.Form["username"];  
        string password = context.Request.Form["password"];  
        string message = null;  
        if (string.IsNullOrEmpty(username))  
        {  
            message = "用户名不能为空";  
            context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");//此JSON格式非常重要,否则会执行jquery的的error函数  
            context.Response.End();  
        }  
        if (string.IsNullOrEmpty(password))  
        {  
            message = "密码不能为空";  
            context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");  
            context.Response.End();  
        }  
        if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))  
        {  
            if (username.ToUpper() == "ADMIN" && password == "123")  
            {                  
                message = "登录成功";  
                context.Response.Write("{\"success\":true,\"message\":\"" + message + "\"}");  
            }  
            else  
            {  
                message = "用户名或密码错误";  
                context.Response.Write("{\"success\":false,\"message\":\"" + message + "\"}");  
            }  
        }  
        context.Response.End();  
         
    }  
   
    public bool IsReusable {  
        get {  
            return false;  
        }  
    }  
  
}
服务器端

 

非跨域情况下参考代码3 ajax请求asmx

$.ajax({
    type: "POST", //Post传参
    url: this.localHanler + '?Method=Login&username=' + $(id_user).val() + '&password=' + $(id_password).val(),
    async:false,
    contentType: "application/json;charset=utf-8",
    timeout: 3000,
    success: function (result) {


        // var str = '{"name":"huangxiaojian","age":"23"}'//单引号写在{}外,每个属性名都必须用双引号,否则会抛出异常。
        // JSON.parse(str)
        // JSON.stringify(a)
        var status_obj = eval(result)[0];

        if (status_obj.b_user_passed == true) {
            // login success
            that.saveUserInfo();
            show_msg('登录成功!正在为您跳转...', '../../index.html'); // /index.html
        }
        else {
            alert("账号密码不一致,请重新检查后再登录!");
        }
        
    },
    error: function (e) {
        alert("请求登录失败!");
        show_loading(false);
    }
});
Ajax请求

 

/// <summary>
/// 非跨域情况下的Ajax直接请求asmx方式
/// 重要经验!
/// 2017.12.21 1002
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
[WebMethod(Description = "登录;非跨域", EnableSession = true)]
public void LoginHandle(string username, string password)
{
    
    DataResult data;
    string result = "";
    DataContractJsonSerializer json;

    data = LoginProcess(username, password);

    json = new DataContractJsonSerializer(data.GetType());
    using (MemoryStream stream = new MemoryStream())
    {
        json.WriteObject(stream, data);
        result = Encoding.UTF8.GetString(stream.ToArray());
    }

    Context.Response.ContentType = "application/json;charset=utf-8";
    Context.Response.Write(result);//这条返回纯json格式数据
    // return result;
}  
服务器端

 

 

 

2 注意事项

同时注意不同类型的数据的处理:

1. 文本

Response.Write(strJson);中的strJson格式为

jsonX = string.Format("{{ id: {0}, pId:{1}, name:\"{2}\", t:\"{3}\",path:\"{4}\",iconSkin:\"{5}\"}}", ffid, 0, name, name, "", iconSkin);

“[json1,json2,...,jsonN]”

的形式生成。

2. blob

可参考如下代码段处理

 

        #region 多媒体信息显示处理

        /// <summary>
        /// 根据bsm和ffid获取图片的二进制数据并返回
        /// </summary>
        public void GetXM_Datas()
        {
            string bsm, ffid, strSRC,fileExt;
            XMXXOperate.XMXXOperateSoapClient tsvc;

            bsm = Request["bsm"].ToString();
            ffid = Request["ffid"].ToString();
            fileExt = Request["exten"].ToString();
 
            tsvc = new XMXXOperate.XMXXOperateSoapClient();
            strSRC = tsvc.GetXMPICSSRC(bsm, ffid);
            if (strSRC == "")
            {
                Response.Write("Error:文件不存在,请重试或联系管理员!");
                return;
            }


            if (fileExt==".jpg")
            {
                // 调用图片处理模块,并返回二进制图片数据
                GetServerPicBlob(strSRC);
            }
            else if (fileExt==".mp4")
            {
                Response.Write(strSRC);
            }
            else if (fileExt == ".srt") 
            {
                GetVideoPathData(strSRC);
            }
           
        }

        private void GetServerPicBlob(string strPicPath)
        {

            Stream iStream = null;
            MemoryStream ms = null, ms2 = null;
            int buffer_size = 1024 * 100;
            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[buffer_size];
            // Length of the file:
            int length;
            // Total bytes to read:
            long dataToRead;
            // Identify the file to download including its path.
            string filepath = HttpContext.Current.Request.MapPath("..//" + strPicPath);//data_test.png,oceans-clip.png, uav_image.jpg
            // Identify the file name.
            string filename = System.IO.Path.GetFileName(filepath);

            try
            {

                Response.ContentType = "image/png";//问题就在这里,解决百M关口 //http://www.cnblogs.com/huanhuan86/archive/2012/06/12/2546362.html
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);

                // Open the file.
                //iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);//用文件流来处理
                // Total bytes to read:
                //dataToRead = iStream.Length;


                // 图片加水印,缩略处理
                //byte[] byDataImg = new byte[iStream.Length];
                //iStream.Read(byDataImg, 0, byDataImg.Length);
                //iStream.Close();

                //ms = new MemoryStream(byDataImg);
                //byDataImg = null;

                // draw water shade
                Image img, img_small;
                Font ft,ft2;
                Brush b;
                Graphics g;
                SizeF szStr;
                Size smalledImg;
                Point location_str;
                string strCopyWrite;
                // initial
                img = Image.FromFile(filepath);//img = Image.FromStream(ms);
                smalledImg = GetFittedImageSize(img.Size);
                img_small = new Bitmap(smalledImg.Width, smalledImg.Height);
                //ms.Dispose();


                g = System.Drawing.Graphics.FromImage(img_small);
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                b = new SolidBrush(Color.FromArgb(80, 0, 255, 255));
                ft = new Font("宋体", Math.Max(Math.Min((int)(img_small.Height * 0.048), 36), 10), FontStyle.Italic);
                ft2 = new Font("Times New Roman", 8, FontStyle.Italic);
                strCopyWrite  = string.Format("ZJECMS Media ©{0} ZJHH", DateTime.Now.Year);
                szStr = g.MeasureString(strCopyWrite, ft);
                location_str = new Point((int)(img_small.Width * 0.95 - szStr.Width),(int)(img_small.Height * 0.95 - szStr.Height));
               
                // draw
                g.DrawImage(img, 0, 0, img_small.Width, img_small.Height);// new Rectangle(0, 0, img.Width, img.Height)
                g.DrawString(strCopyWrite, ft, b, location_str);
                g.DrawString(string.Format("Scale {0}×{1}", img.Width, img.Height), ft2, b, location_str.X, location_str.Y+15);
                g.DrawLine(new Pen(new SolidBrush(Color.FromArgb(8, 255, 0, 0)), 5), 0, 0, 500, 500);
                ms2 = new MemoryStream();
                img_small.Save(ms2, System.Drawing.Imaging.ImageFormat.Png);
                // dispose
                g.Dispose();
                img.Dispose();
                img_small.Dispose();
                b.Dispose();
                ft.Dispose();
                ft2.Dispose();

                //img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png); 
                //context.Response.End(); 

                // Read the bytes.
                dataToRead = ms2.Length;
                ms2.Position = 0; // 这个必须要有
                while (dataToRead > 0)
                {
                    // Verify that the client is connected.
                    if (Response.IsClientConnected)
                    {
                        // Read the data in buffer.
                        length = ms2.Read(buffer, 0, buffer_size);
                        // Write the data to the current output stream.
                        Response.OutputStream.Write(buffer, 0, length);
                        // Flush the data to the HTML output.
                        Response.Flush();

                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                // Trap the error, if any.
                Response.Write("Error : " + ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                if (ms2 != null)
                {
                    ms2.Close();
                }
            }

        }

        private Size GetFittedImageSize(Size size)
        {

            float scale_w, scale_h, scale;
            Size size_new;

            size_new = new Size();
            if (size.Width< cvs_width && size.Height< cvs_height)
            {
                size_new = size;
            }
            else if (size.Width>=cvs_width && size.Height< cvs_height)
            {
                // scaled by width
                scale_w = (float)cvs_width / size.Width;
                size_new.Width = cvs_width;
                size_new.Height = (int)(size.Height * scale_w + 0.5);
            }
            else if (size.Width < cvs_width && size.Height >= cvs_height)
            {
                // scaled by height
                scale_h = (float)cvs_height / size.Height;
                size_new.Width = (int)(size.Width * scale_h + 0.5);
                size_new.Height = cvs_height;
            }
            else
            {
                scale_w = (float)cvs_width / size.Width;
                scale_h = (float)cvs_height / size.Height;

                scale = scale_w <= scale_h ? scale_w : scale_h;
                size_new.Width = (int)(size.Width * scale+ 0.5);
                size_new.Height = (int)(size.Height * scale + 0.5);
            }


            return size_new;
        }

        
        private void GetVideoPathData(string strSRC)
        {

            // 解析文件,并生成坐标序列数据传递到前端调用百度地图进行显示
            // F:\Learnings\BS\PublishNet\DATA\X2017071412954_无人机巡查\2、原始资料\原始资料\1临安\原始数据\昌北溪\视频
            // 2017.7.31
            FrameLocation parsedData;
            string json,filepath;


            filepath = HttpContext.Current.Request.MapPath("..//" + strSRC);
            parsedData = SRTParse.ParseSRTFile(filepath);

            // 返回JSON数据,由前端解析并在Canvas中绘制
            //IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd hh:mm:ss" };
            json = Newtonsoft.Json.JsonConvert.SerializeObject(parsedData/*, Newtonsoft.Json.Formatting.Indented, timeConverter*/);


            Response.Write(json);
        }

        #endregion
二进制数据的处理与返回

 

posted @ 2017-09-06 09:48  wenglabs  阅读(55)  评论(0编辑  收藏  举报