> For the complete documentation index, see [llms.txt](https://johch3n611u.gitbook.io/c50108/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://johch3n611u.gitbook.io/c50108/ju-li-cheng-bei/201904/20190415-qian-duan-jqajax+json-duan.md).

# 2019/0415/前端JQ-Ajax+JSON&後端ADO建置、主板頁面概念控制項、Bootstrap演示

前端程式設計最後一PART&#x20;( AJAX JSON )
-------------------

第29有試過抓取GOOGLE API拋出來的資料 ( 前五筆免前

第三方api

Application Interface 程式用的介面

Ui user Interface

為了要跨裝置，不像以前單純

Client -> api -> server 完全分開

無論是增刪修

與後端溝通必須要有個標準

但前端設備太多了

所以需要api做整合

以前用 xml soap

現在改為 json

### 範例 : 農委會開放平台&#xD;

更新速度非常快

資料格式非常多 json csv excel word xml

以後的資料不一定都跟資料庫溝通

有種方式為 nosql

有資料介接說明文件甚至有版本

json不管是什麼資料都必須要放在雙引號內

ctrl c 回vs

前端專案增加新項目ｊｓｏｎ檔案

Ctrl v 就很清楚結構

其實就是一堆的集合\[ ]

每筆資料{ }

“Key”:”value”, 表示法

![](/files/-LcVcvi1NFAnkLSBKTE7)

#### 利用ｕｒｌ取資料&#xD;

就想像把ａｐｉ想像為函數

必須要有技術文件才看得懂設計

![](/files/-LcVd1SzHUhXUOAXuqKg)

第一ｈｔｍｌ

第二ｊｑ

第三ｄｏｍ

以往ｊｓ寫ａｊａｘ非常麻煩

現在利用ｊｑ來寫

#### ｊｑ寫ａｊａｘ&#xD;

#### 利用ａｊａｘ方法　跟　ａｐｉ要資料&#xD;

＄.ajax(); 方法

Ajax->局部更新

Ux Experience

不用整個網頁做ｐｏｓｔ也可以向伺服器提出要資料

ｔｙｐｅ：

ｈｔｔｐ有兩種傳遞資料方式ｇｅｔ　ｐｏｓｔ

ｕｒｌ：

ｊｓｏｎ位址，（像是背景資料非同步有拿到資料或沒拿到都不會看到報錯

ｆｏｒｍａｔ：

指定ａｐｉ拋回之資料格式，以往預設是ｘｍｌ

ｓｕｃｃｅｓｓ：

成功抓取資料的話執行後續函式

ｅｒｒｏｒ：

失敗了執行後續函式

#### 將資料顯示（ｄｏｍ資料）&#xD;

可以換顯示順序或顯示筆數或樣式

### 題外話：&#xD;

表格不適合響應式，卡片才適合。

不知道幾筆所以要用迴圈控制

順道知道ｈｔｍｌ５語意ｔｈｅａｄ、ｔｂｏｄｙ

傳入ｄａｔａ（ｊｓｏｎ資料）參數進函數使用

欄位位址．欄位名稱

ｄａｔａ［ｉ］．ＡＶＧＰＲＩＣＥ

ＰＲＧＲＡＳ?? preload??　有時筆數資料太多　必須讓使用者知道正在讀取

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <table id="tb1" border="1">
        
    </table>


    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
        $.ajax({
            type: 'GET',
            url: 'ProductPrice.json',
            format: 'json',
            success: function (data) {
                //alert('Success!!');
                $('#tb1').append("<thead><tr><th>品項名稱</th><th>報價</th><th>年</th><th>月</th><th>旬</th><th>鄉鎮農會</th></tr></thead>");
                $('#tb1').append("<tboday>");
                for (var i = 0; i < data.length; i++) {
                    $('#tb1').append("<tr><th>" + data[i].PRODUCTNAME + "</th><th>" + data[i].AVGPRICE + "</th><th>" + data[i].YEAR + "</th><th>" + data[i].MONTH + "</th><th>" + data[i].PERIOD + "</th><th>" + data[i].ORGNAME +"</th></tr>");

                }
                $('#tb1').append("</tboday>");

            },
            error: function () {
                alert('Error!!');
            }

        });


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

```

![](/files/-Ld8YYzRBYpYVAK0B_FB)

加上ｃｓｓ

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        #tb1{
            width:90%;
            margin:auto;
        }
        #tb1 thead tr{
            background-color:#383838;
            color:white;
        }

            #tb1 tbody tr:nth-child(2n+1) {
                background-color:#acacac;
            }
            #tb1 tbody tr:nth-child(2n) {
                background-color:white;
            }

            #tb1 tbody tr:hover {
                background-color:aquamarine;
                color:red;
                border:5px solid black;
            }
    </style>
</head>
<body>
    <table id="tb1">
        
    </table>


    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
     
        $.ajax({
            type: 'GET',
            url: 'ProductPrice.json',
            format: 'json',
            success: function (data) {
                //alert('Success!!');
                $('#tb1').append("<thead><tr><th>品項名稱</th><th>報價</th><th>年</th><th>月</th><th>旬</th><th>鄉鎮農會</th></tr></thead>");
                $('#tb1').append("<tbody>");
                for (var i = 0; i < data.length; i++) {
                    $('#tb1').append("<tr><th>" + data[i].PRODUCTNAME + "</th><th>" + data[i].AVGPRICE + "</th><th>" + data[i].YEAR + "</th><th>" + data[i].MONTH + "</th><th>" + data[i].PERIOD + "</th><th>" + data[i].ORGNAME +"</th></tr>");

                }
                $('#tb1').append("</tbody>");

            },
            error: function () {
                alert('Error!!');
            }

        });


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

```

![](/files/-Ld8YYzSSalMgXHHwySZ)

#### 即時資料&#xD;

{% embed url="<https://ptx.transportdata.tw/PTX>" %}

ＸＭＬ都是標籤比較笨重

資料介接即時資料

ｈｔｔｐｓ通常就能直接介接ｓｓｌ編碼過

ｘｍｌ　ｊｓｏｎ　容易被輕易擷取

{% embed url="<https://ptx.transportdata.tw/MOTC/Swagger>" %}

階層式資料

{% embed url="<https://ptx.transportdata.tw/PTX/Service?Transportation=%E8%87%BA%E9%90%B5>" %}

要自己去想關聯

用ｉｄ就可以互相查詢

#### ｊｓｏｎ如果要顯示第二層的資料的話直接打欄位就好（第二層有兩個欄位）&#xD;

位址．第一層欄位．第二層欄位

邏輯：

１準點或誤點，如果誤點則顯示誤點時間多久

２順行逆行０１判斷

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        #tb1{
            width:90%;
            margin:auto;
        }
        #tb1 thead tr{
            background-color:#383838;
            color:white;
        }

            #tb1 tbody tr:nth-child(2n+1) {
                background-color:#acacac;
            }
            #tb1 tbody tr:nth-child(2n) {
                background-color:white;
            }

            #tb1 tbody tr:hover {
           background-color:aquamarine;
                color:red;
                border:5px solid black;
            }
    </style>
</head>
<body>
    <table id="tb1">
        
    </table>


    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>

        function updateData() {
            $.ajax({
                type: 'GET',
                url: 'https://ptx.transportdata.tw/MOTC/v2/Rail/TRA/LiveBoard?$format=JSON',
                format: 'json',
                success: function (data) {
                    //alert(data.length);
                    var TripLine;
                    var DelayTime;
                    var Direction;
                    $('#tb1').append("<thead><tr><td>站名</td><td>車次</td><td>車種</td><td>山/海線</td><td>行車方向</td><td>到站時間</td><td>發車時間</td><td>誤點時間</td></tr></thead>");
                    $('#tb1').append("<tbody>");
                    for (var i = 0; i < data.length; i++) {
                            switch (data[i].TripLine) {
                                case 0:
                                    TripLine = "不經山海線";
                                    break;
                                case 1:
                                    TripLine = "山線";
                                    break;
                                case 2:
                                    TripLine = "海線";
                                    break;
                        }
                        DelayTime = data[i].DelayTime == 0 ? "準點" : "<span style='color:red'>誤點" + data[i].DelayTime+"分鐘</span>"
                        Direction = data[i].Direction == 0 ? "順行" : "逆行";


                        $('#tb1').append("<tr><th>" + data[i].StationName.Zh_tw + "</th><th>" + data[i].TrainNo + "</th><th>" + data[i].TrainTypeName.Zh_tw + "</th><th>" + TripLine + "</th><th>" + Direction + "</th><th>" + data[i].ScheduledArrivalTime + "</th><th>" + data[i].ScheduledDepartureTime + "</th><th>" + DelayTime + "</th></tr>");

                    }
                    $('#tb1').append("</tbody>");

                },
                error: function () {
                    alert('Error!!');
                }

            });
            setTimeout("updateData()",120000);
        }
        updateData();
    </script>
</body>
</html>

```

![](/files/-Ld8YYzTAbYjsj0HoliD)

#### ＪＳＯＮ階層結構

```
{ 
"StationID": "1001", 
"StationName": { "Zh_tw": "基隆", "En": "Keelung" }, 
"TrainNo": "2134", 
"Direction": 0, 
"TrainTypeID": "1131", 
"TrainTypeCode": "6", 
"TrainTypeName": { "Zh_tw": "區間車", "En": "Local Train" }, 
"TripLine": 1, 
"EndingStationID": "1001", 
"EndingStationName": { "Zh_tw": "基隆", "En": "Keelung" }, "ScheduledArrivalTime": "11:38:00", 
"ScheduledDepartureTime": "11:40:00", 
"DelayTime": 0, 
"SrcUpdateTime": "2019-04-15T11:16:19+08:00", 
"UpdateTime": "2019-04-15T11:17:20+08:00" 
},

```

### 範例 : 關鍵字查詢 ＡＰＩ&#xD;

兩種方式

1．	藉由ＵＲＬ去ＡＰＩ要關鍵資料顯示（要對方ＡＰＩ有寫查詢功能

2．	資料全部抓回來後由程式判別顯示

身為程式設計師就是要抓回來寫邏輯判斷

清空ＴＡＢＬＥＤ讓資料不會附加上去

ＳＥＴＩＮＴＥＲＶＡＬ每隔多少區間呼叫一次

ＳＥＴＴＩＭＥＯＵＴ差別是第二種一開始必須有人呼叫一次

```
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        #tb1{
            width:90%;
            margin:auto;
        }
        #tb1 thead tr{
            background-color:#383838;
            color:white;
        }

            #tb1 tbody tr:nth-child(2n+1) {
                background-color:#acacac;
            }
            #tb1 tbody tr:nth-child(2n) {
                background-color:white;
            }

            #tb1 tbody tr:hover {
               background-color:aquamarine;
                color:red;
                border:5px solid black;
            }
    </style>
</head>
<body>
    <input id="StationName" type="text" /><input id="Button1" type="button" value="查詢" />
    <table id="tb1">
        
    </table>


    <script src="Scripts/jquery-3.3.1.min.js"></script>
    <script>
        var StationName;
        $('#Button1').click(function () {
            StationName = $('#StationName').val();
            updateData(StationName);
        });

        setInterval(function () { updateData($('#StationName').val()) }, 120000);

        function updateData(StationName) {
            $('#tb1').empty();
            $.ajax({
                type: 'GET',
                url: 'https://ptx.transportdata.tw/MOTC/v2/Rail/TRA/LiveBoard?$format=JSON',
                format: 'json',
                success: function (data) {
                    //alert(data.length);
                    var TripLine;
                    var DelayTime;
                    var Direction;
                    $('#tb1').append("<thead><tr><td>站名</td><td>車次</td><td>車種</td><td>山/海線</td><td>行車方向</td><td>到站時間</td><td>發車時間</td><td>誤點時間</td></tr></thead>");
                    $('#tb1').append("<tbody>");
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].StationName.Zh_tw == StationName) {
                            switch (data[i].TripLine) {
                                case 0:
                                    TripLine = "不經山海線";
                                    break;
                                case 1:
                                    TripLine = "山線";
                                    break;
                                case 2:
                                    TripLine = "海線";
                                    break;
                            }
                            DelayTime = data[i].DelayTime == 0 ? "準點" : "<span style='color:red'>誤點" + data[i].DelayTime + "分鐘</span>"
                            Direction = data[i].Direction == 0 ? "順行" : "逆行";


                            $('#tb1').append("<tr><th>" + data[i].StationName.Zh_tw + "</th><th>" + data[i].TrainNo + "</th><th>" + data[i].TrainTypeName.Zh_tw + "</th><th>" + TripLine + "</th><th>" + Direction + "</th><th>" + data[i].ScheduledArrivalTime + "</th><th>" + data[i].ScheduledDepartureTime + "</th><th>" + DelayTime + "</th></tr>");
                        }
                    }
                    $('#tb1').append("</tbody>");

                },
                error: function () {
                    alert('Error!!');
                }

            });
            
        }
        //updateData();
    </script>
</body>
</html>

```

![](/files/-Ld8YYzUdXHr9EGGX_7a)

### 補充&#xD;

ＰＴＸ有ＧＩＴＨＵＢ／ＧＩＴＢＯＯＫ等開放服務

<https://ptx.transportdata.tw/PTX/>

<https://github.com/ptxmotc/Sample-code>

<https://ptxmotc.gitbooks.io/ptx-api-documentation/content/>

示範應用

<https://ptx.transportdata.tw/PTX/Demo/Example>

其實程式就是這個樣子做出來！

ＡＰＩ串接的程式，客戶端可以直接執行，但是要有網路。

下午後端&#x20;webform 準備踏入 MVC
----------------------

前段課程如果要刪除資料 實務上會一起刪除 ( 刪除明細後再刪除主要資料&#x20;)

同一個功能無法用ｗｅｂｆｏｍｅ轉ＭＶＣ

但能夠放在同一個專案裡面

#### &#xD;ＭＶＣ７個步驟但是是最多不是每次都７個

![](/files/-LcVffQ-Zwla5CgLyTZ4)

ＷｅｂＦｏｒｍ－＞ＭＶＣ

要在ＷｅｂＦｏｒｍ內建立Ｍｏｄｅｌ

藉由Ｅｎｔｉｔｙ　Ｆｒａｍｅｗｏｒｋ

直接操作資料庫

之前有學過（ＤａｔａＳｏｕｃｅＣｏｎｔｒｏｌ、ＡＤＯ．ｎｅｔ

以下使用 空白專案同時建置 使用ADO.net串接資料庫

演示 Ｗｅｂｆｏｒｍ　變　ＭＶＣ

### 建置環境&#xD;

![](/files/-Ld8YYzVl5yUP7j-p7Kd)

![](/files/-Ld8YYzWeI4J1K0-uv13)

![](/files/-Ld8YYzXVpFTgQrkbmL3)

![](/files/-Ld8YYzYK5yqv8iBH8cq)

#### MVC

１模型從資料庫來

２空的要自己畫模型

３沒有資料庫也沒有模型但用編程方式建立模型產生資料庫？？

４利用現有資料庫建立ｃｏｄｅ產生模型

Webfome 透過 Ｅｎｔｉｔｙ做新刪修

Gridview 讀資料 現在開始讀寫都不會用到sql而是entity

![](/files/-Ld8YYzZtB5SuoxkeWoT)

![](/files/-Ld8YYz_ppgZ7FfbtMHO)

![](/files/-Ld8YYza6E2bFkr9HIOY)

![](/files/-Ld8YYzbdeiV0eTR9BX-)

以上截圖僅為參考需要考慮其原理更改自訂id等等…

如果有問題最好直接整個方案刪除一步步重來

完成 ADO.net 繫結後&#x20;

![](/files/-Ld8YYzcOo_PE8jUtPpS)

![](/files/-Ld8YYzd-zODQddOqH33)

需要建置編碼

#### 題外話:&#xD;

指標

堆疊演算法

## 主板頁面概念 Contentplaceholder 控制項

![](/files/-LcVgv_5aE44Wi-5qEm9)

![](/files/-LcVgxTQ5nJ_G8CmiSpc)

![](/files/-Ld8YYzeuuzleo2wnWwF)

![](/files/-Ld8YYzg3e5XyhqhzPZB)

![](/files/-Ld8YYzfzyQqJnsExoyW)

![](/files/-Ld8YYzhpIYi63mPIpm4)

![](/files/-Ld8YYziQbBHe2E9PC1Q)

![](/files/-Ld8YYzjW6v3EUgS2R2p)

Bootstrap UI介面 3.4.1 (版本很重要不可互用)

有

![](/files/-Ld8YYzkb-4xUV3K_pU1)

無

![](/files/-LcVhXVzARS_m015e20q)

![](/files/-Ld8YYzlP0-cpZjX1xS5)

#### Index.aspx

```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MVC1.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView1" runat="server"></asp:GridView>

        </div>
    </form>
</body>
</html>
###Index.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MVC1.Models;

namespace MVC1
{
    public partial class Index : System.Web.UI.Page
    {
        dbProductEntities db = new dbProductEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = db.tProduct.ToList();
            GridView1.DataBind();
        }
    }
}

```

#### Index2.aspx

```
<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="MVC1.Index2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <h2>產品列表</h2>
    <p>
        <a href="Create.aspx">新增產嘽品</a>
    </p>
    <asp:GridView ID="GridView1" runat="server" CssClass="table" AutoGenerateColumns="False" GridLines="None">
        <Columns>
            <asp:BoundField DataField="fId" HeaderText="產品編號" />
            <asp:BoundField DataField="fName" HeaderText="產品名稱" />
            <asp:BoundField DataField="fPrice" HeaderText="單價" DataFormatString="{0:C}" />
            <asp:ImageField DataImageUrlField="fImg" DataImageUrlFormatString="images/{0}" ControlStyle-Width="150px" HeaderText="圖示">
            <ControlStyle Width="150px"></ControlStyle>
            </asp:ImageField>
        
            <asp:TemplateField ShowHeader="False">
                <ItemTemplate>
                    <asp:LinkButton ID="lnkEdit" runat="server">編輯</asp:LinkButton>
                    |
                    <asp:LinkButton ID="lnkDelete" runat="server">刪除</asp:LinkButton>

                </ItemTemplate>

            </asp:TemplateField>
        
        </Columns>

    </asp:GridView>

</asp:Content>

```

#### Index2.aspx.cs

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MVC1.Models;

namespace MVC1
{
    public partial class Index2 : System.Web.UI.Page
    {
        dbProductEntities db = new dbProductEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = db.tProduct.ToList();
            GridView1.DataBind();
        }
    }
}


```

#### Site1.Master

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MVC1.Models;

namespace MVC1
{
    public partial class Index2 : System.Web.UI.Page
    {
        dbProductEntities db = new dbProductEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            GridView1.DataSource = db.tProduct.ToList();
            GridView1.DataBind();
        }
    }
}

```

#### Site1.Master

```
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="MVC1.Site1" %>

<!DOCTYPE html>

<html>
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>農易旺</title>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <link href="Content/Site.css" rel="stylesheet" />
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">

        <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" runat="server" href="Index.aspx">產品管理系統</a>
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a runat="server" href="Index2.aspx">產品列表</a></li>
                        <li><a runat="server" href="Create.aspx">產品新增</a></li>
                        <li><a runat="server" href="About.aspx">關於本站</a></li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="container body-content">
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        
        <hr />
        <footer>
            <p> &copy; <%: DateTime.Now.Year %> 農易旺版權所有</p>
        </footer>
        </div>
    </form>
</body>
</html>


```
