jQuery post數據至ashx


今天給大家分享一個小功能,在jQuery環境中,Post data to ashx進行數據交互。

參考下面代碼示例:

 

$.ajax({
                     url: '<%= ResolveUrl("~/Handlers/xxx.ashx") %>',
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            data: JSON.stringify({
                                top: 10,
                                term: request.term
                            }),
                            success: function (data) {
                                //...
                            }
                        });
Source Code


jQuery的Post值是使用type: "POST",上傳的數據類型為contentType: "application/json; charset=utf-8"。

從代碼示例中,它有2個參考需要上傳,top,term。

為了更好在ashx能接收,我們寫一個model:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Param
/// </summary>
namespace Insus.NET
{
    public class Param
    {
        private int _top;
        public int Top
        {
            get { return _top; }
            set { _top = value; }
        }


        private string _term;

        public string Term
        {
            get { return _term; }
            set { _term = value; }
        }
    }
}
Source Code


在ashx處理程序中,我們可以同下面這樣接收Post過來的數據:

 

public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;

            Stream inputStream = context.Request.InputStream;
            Encoding encoding = context.Request.ContentEncoding;
            StreamReader streamReader = new StreamReader(inputStream, encoding);

            string strJson = streamReader.ReadToEnd();

            Param p = JsonConvert.DeserializeObject<Param>(strJson);

            int top = Convert.ToInt32(p.Top);
            string term = p.Term;

           
            //var result = ...
            //context.Response.Write(result.ToJson());
        }
Source Code


下面我們嘗試在實際環境中,Post一個數據如 “1628”,在FireFox的firebug看到傳送結果如下:


 

在ashx中,接收到的結果如下:

 

再進一步得到top的值:

 

最后得到的是term的值:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM