iT邦幫忙

3

ajax + aspx(入門)

後端回傳字串給前端
1.建立後端aspx
2.建立前端html (ajax呼叫aspx)

#ASPX
新增專案
新增aspx
把html都刪掉,只留

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication2.aspx.WebForm1" %>

.cs的部分

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write("hihi");
            Response.End();
        }

#ajax
新增html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="../js/jquery-3.2.1.js" type="text/javascript"></script> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <div id="result"></div>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "WebForm1.aspx",
                type: 'POST', 
                success: function (data) {
                    $('#result').text(data);
                },
                error: function (err) {
                    console.log("err:");
                    console.log(err);
                    alert(err);
                }
            });
        });
    </script>
</body>
</html>

#測試
html 右鍵 在瀏覽器中檢視 https://ithelp.ithome.com.tw/upload/images/20171017/201067641BcDfibYVh.png
進階
將js由html抽離開來
#js

$(document).ready(function () {
    $.ajax({
        url: "WebForm1.aspx",
        type: 'POST',
        success: function (data) {
            $('#result').text(data);
        },
        error: function (err) {
            console.log("err:");
            console.log(err);
            alert(err);
        }
    });
});

#html
匯入js

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="../js/jquery-3.2.1.js" type="text/javascript"></script> 
    <script src="js1.js" type="text/javascript"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <div id="result"></div> 
</body>
</html>

#測試
html 右鍵 在瀏覽器中檢視 https://ithelp.ithome.com.tw/upload/images/20171017/201067641BcDfibYVh.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言