Json是一種資料格式, 以下是參考網站(多國語系)
http://www.json.org/

在jQuery中有不同的傳輸方式(可參考http://api.jquery.com/jQuery.post/)

在這裡說明是aspx && jQuery的方式
事實上在aspx裡可以透過ashx或是apsx的頁面做資料的回傳
在程式內都標明了 "context.Response.ContentType = "text/plain";"
代表資料傳回為文字(直接連網址的話,會看到結果就像一個txt的文字檔呈現在瀏覽器上)

在apsx的頁面中(jQuery請自行學習, 在此不多說明)

<script type="text/javascript">

//這段是說明一個textbox (id = txtCR) 內容改變時, 呼叫getdata的method
    $('#txtCR').change(function () {
            getdata();
         });
///

而在jQuery中對於ajax的資料呼叫格式如下:
$.post("呼叫的檔案路徑", json格式的值 , function(回傳的傳)
{判斷式}, "指明傳輸的格式");


程式碼如下:
function getdata() {
    $.post("Handler.ashx", { crno: $("#txtCR").val() }, function(data) {
               if (data != null) {
                   $("#HintString").text('Data_Exsited');
                } else {
                   alert('No Data');
                }
            }, "json");
       }
///
</script>

1、ashx的頁面
(致於如何在aspx的專案中加入.ashx的頁面,請按滑鼠右鍵選擇add new item 自已找!)

public class Handler : IHttpHandler {
    public void ProcessRequest (HttpContext context) { //透過http (廢話)
        context.Response.ContentType = "text/plain"; //標註頁面為text        
        string id2 = context.Request["crno"]; //接收ajax所傳過來的值
    id2 = id2 + "Hello World";       
        factor = JsonPaser.JsonCreateDataFormat(ds);
    //回傳也必需為json格式, 在此筆者是自行寫一段程式碼去編譯的
        context.Response.Write(factor); //此動作為回傳
    }

2、aspx頁面
在頁面部分,把所有HTML tag都清空,只留下第一行的Tag
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="json.aspx.cs" Inherits="json" %>
然後在.cs頁面的Page_load中寫入
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Request["crno"].Equals(""))
        {
            //取得變數ID
            string id2 = Request["crno"].ToString();
         id2 = id2 +"hello World";
        //最後就是把撈出來的JSON字串Response.Write出來
            Response.Write(id2);
        }
    }

arrow
arrow
    文章標籤
    json c# httpcontext jQuery
    全站熱搜

    斷了線的小木偶 發表在 痞客邦 留言(0) 人氣()