iT邦幫忙

0

如何在網頁上print 出 AJAX POST 給ASP.NET的 data

請問各位高手
小弟目前正在做一個練習
功能是使用jQ AJAX POST資料給後端之後,再回傳到前台顯示

以下是page1.aspx部分

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="page1.aspx.cs" Inherits="page1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="//code.jquery.com/jquery-1.6.1.js" type="text/javascript"></script>
    
</head>
<body>

    <h1>請選擇商品</h1>
    <form id="os-form">
        <h1>作業系統</h1>
        <input type="checkbox" name="item2" id="mac" value="macOS">
        <label for="mac">mac</label>
        <br>

        <input type="checkbox" name="item3" id="android" value="android">
        <label for="android">android</label>
        <br>

        <input type="checkbox" name="item4" id="windows" value="windows">
        <label for="windows">windows</label>
        <br>

        <input type="checkbox" name="item5" id="linux" value="linux">
        <label for="linux">linux</label>
        <br>

     
        <h1>軟體</h1>
        <input type="checkbox" name="item1" id="word" value="word">
        <label for="word">word</label>
        <br>

        <input type="checkbox" name="item2" id="ppt" value="ppt">
        <label for="ppt">ppt</label>
        <br>

        <input type="checkbox" name="item3" id="photoshop" value="photoshop">
        <label for="photoshop">photoshop</label>
        <br>

        <input type="checkbox" name="item4" id="skype" value="skype">
        <label for="skype">skype</label>
        <br>

        <input type="checkbox" name="item5" id="excel" value="excel">
        <label for="excel">excel</label>
        <br>

        <input type="checkbox" name="item5" id="雲" value="雲">
        <label for="雲">雲</label>
        <br>

        <input type="button" value="送出" id="submit">
    </form>


    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>

    <script>

        $(document).ready(function () {

            var item = $('#os-form input[type="checkbox"]')

            var ary = [];


            function ajaxpost() {

                //push進陣列
                for (i = 0; i < item.length; i++) {
                    if (item[i].checked) {
                        ary.push(item[i].value);
                    }
                }
                
                console.log(ary);


                if (ary.length === 0) {
                    alert('你沒有選東西')
                    return
                }

                $.ajax({
                    type: "POST",
                    url: "json.aspx",
                    data: {
                        "obj": ary,
                    },
                    traditional: true,
                    // dataType: "text",
                    success: function (response) {
                        // console.log(this);
                        alert(response);
                        console.log(this)
                        ary = [];
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.readyState);
                        alert(XMLHttpRequest.status);
                        alert(XMLHttpRequest.responseText);

                        alert(response);
                        // alert(console.error(url, status, err.toString()));
                        console.log(this.data)
                    }.bind(this)
                });
            }

            var submitBtn = $('#submit');
            submitBtn.on('click', ajaxpost);

        });

    </script>
</body>
</html>

我的問題是:該如何在後端取得AJAX所傳遞的data呢?

我知道如果要在前端print的話會要使用Response.Write()

但對於C#語法不熟,還請多指教


補充

不好意思,還是有點問題,想請問是不是哪邊沒寫好導致網頁alert的時候是空白的呢?

這是json.aspx.cs

using System;

//private string sId = HttpRequest.Params["obj"]
public partial class json : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string obj = Request.Form["obj"];

        Response.Write(obj);
        Response.End(); 
    }
}

這是json.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="json.aspx.cs" Inherits="json" %>
神Q超人 iT邦研究生 5 級 ‧ 2018-09-03 14:07:09 檢舉
print是用Response.Write()沒錯
context.Response.Write[string]

要取值的話就用Request()!所以這樣子取看看吧!
string obj = context.Request["obj"]
Homura iT邦高手 1 級 ‧ 2018-09-03 14:07:38 檢舉
@神Q超人你那樣讀會讀到Form以外的值唷
larrykkk iT邦新手 5 級 ‧ 2018-09-03 14:10:51 檢舉
@神Q超人 我試試看
@Homura 忘記改成aspx了XD 之前的php寫得很簡單,收到post資料後吐一個"ok" 給前端alert而已,而現在是想要在.aspx裡面吐回去收到的post資料
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

4
Homura
iT邦高手 1 級 ‧ 2018-09-03 14:09:36
最佳解答

如果是.aspx.cs
Request.Form["obj"]
如果是.ashx
Context.Request.Form["obj"]

看更多先前的回應...收起先前的回應...
神Q超人 iT邦研究生 5 級 ‧ 2018-09-03 14:15:29 檢舉

原來Request底下還有一個Form/images/emoticon/emoticon16.gif

Homura iT邦高手 1 級 ‧ 2018-09-03 14:18:01 檢舉

神Q超人
對啊
還有QueryString
你如果沒加他會都找
這樣有點危險

larrykkk iT邦新手 5 級 ‧ 2018-09-03 14:26:42 檢舉

不好意思,還是有點問題,想請問是不是哪邊沒寫好導致網頁alert的時候是空白的呢?

這是json.aspx.cs

using System;

//private string sId = HttpRequest.Params["obj"]
public partial class json : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string obj = Request.Form["obj"];

        Response.Write(obj);
        Response.End(); 
    }
}

這是 page1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="page1.aspx.cs" Inherits="page1" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="//code.jquery.com/jquery-1.6.1.js" type="text/javascript"></script>
    
</head>
<body>

    <h1>請選擇商品</h1>
    <form id="os-form">
        <h1>作業系統</h1>
        <input type="checkbox" name="item2" id="mac" value="macOS">
        <label for="mac">mac</label>
        <br>

        <input type="checkbox" name="item3" id="android" value="android">
        <label for="android">android</label>
        <br>

        <input type="checkbox" name="item4" id="windows" value="windows">
        <label for="windows">windows</label>
        <br>

        <input type="checkbox" name="item5" id="linux" value="linux">
        <label for="linux">linux</label>
        <br>

     
        <h1>軟體</h1>
        <input type="checkbox" name="item1" id="word" value="word">
        <label for="word">word</label>
        <br>

        <input type="checkbox" name="item2" id="ppt" value="ppt">
        <label for="ppt">ppt</label>
        <br>

        <input type="checkbox" name="item3" id="photoshop" value="photoshop">
        <label for="photoshop">photoshop</label>
        <br>

        <input type="checkbox" name="item4" id="skype" value="skype">
        <label for="skype">skype</label>
        <br>

        <input type="checkbox" name="item5" id="excel" value="excel">
        <label for="excel">excel</label>
        <br>

        <input type="checkbox" name="item5" id="雲" value="雲">
        <label for="雲">雲</label>
        <br>

        <input type="button" value="送出" id="submit">
    </form>


    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>

    <script>

        $(document).ready(function () {

            var item = $('#os-form input[type="checkbox"]')

            var ary = [];


            function ajaxpost() {

                //push進陣列
                for (i = 0; i < item.length; i++) {
                    if (item[i].checked) {
                        ary.push(item[i].value);
                    }
                }
                
                console.log(ary);


                if (ary.length === 0) {
                    alert('你沒有選東西')
                    return
                }

                $.ajax({
                    type: "POST",
                    url: "json.aspx",
                    data: {
                        "obj": ary,
                    },
                    traditional: true,
                    // dataType: "text",
                    success: function (response) {
                        // console.log(this);
                        alert(response);
                        console.log(this)
                        ary = [];
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest.readyState);
                        alert(XMLHttpRequest.status);
                        alert(XMLHttpRequest.responseText);

                        alert(response);
                        // alert(console.error(url, status, err.toString()));
                        console.log(this.data)
                    }.bind(this)
                });
            }

            var submitBtn = $('#submit');
            submitBtn.on('click', ajaxpost);

        });

    </script>
</body>
</html>

這是json.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="json.aspx.cs" Inherits="json" %>
Homura iT邦高手 1 級 ‧ 2018-09-03 14:32:56 檢舉

larrykkk
因為你沒有ContenType
還有aspx會送回整頁html
json.aspx的Page_Load()改這樣

// 清空原有.apsx內容
Response.Clear();
// 定義送出的ContentType
Response.ContentType = "text/plain"; 
// 抓取Form的obj值
string obj = Request.Form["obj"];
// 寫入obj
Response.Write(obj);
Response.End(); // 停止執行並送出

js的dataType: "text"要對應
註解要拿掉

larrykkk iT邦新手 5 級 ‧ 2018-09-03 14:48:33 檢舉

Homura
請問您的意思是將.aspx的內容改成用.html副檔名嗎

我試過了也參照您的做法還是一樣是空白一片/images/emoticon/emoticon02.gif

Homura iT邦高手 1 級 ‧ 2018-09-03 14:50:50 檢舉

larrykkk
當然不是啊/images/emoticon/emoticon04.gif
他原本就會送回Html
是說你要先把原本要送出的內容清空
上面的Response.Clear()是清空原有的Html內容!

我上面加了註解看一下...

larrykkk iT邦新手 5 級 ‧ 2018-09-03 15:00:46 檢舉

json.aspx部分

using System;

//private string sId = HttpRequest.Params["obj"]
public partial class json : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Clear();
        Response.ContentType = "text/plain";
        string obj = Request.Form["obj"];

        Response.Write(obj);
        Response.End(); 
    }
}

page1.aspx JS部分

...
                $.ajax({
                    type: "POST",
                    url: "json.aspx",
                    data: {
                        "obj": ary,
                    },
                    traditional: true,
                    dataType: "text",
                    success: function (response) {
                        // console.log(this);
                        alert(response);
                        console.log(this)
                        ary = [];
                },
...

/images/emoticon/emoticon06.gif

還是alert出空白a_a

Homura iT邦高手 1 級 ‧ 2018-09-03 15:14:04 檢舉

larrykkk
我試可以耶
你開F12開發者工具
看看Console有什麼錯誤嗎?

阿我剛剛看新版的webform會因為Router重新寫入
導致讀不到
例如我urlDefault.aspx會讀不到
改成Default就行....
你試試看是這原因嗎?

larrykkk iT邦新手 5 級 ‧ 2018-09-03 15:22:24 檢舉

Homura
我另開了一個空白專案在貼進去就解決了,太感謝您了!!

另外也要謝謝神Q超人
/images/emoticon/emoticon12.gif

神Q超人 iT邦研究生 5 級 ‧ 2018-09-03 16:23:27 檢舉

Homura大大
所以有沒有Form類似於全域和區域的感覺嗎XD

larrykkk大大
沒啦!我只是路過而已,哈哈。

Homura iT邦高手 1 級 ‧ 2018-09-03 16:44:19 檢舉

神Q超人
是的

我要發表回答

立即登入回答