環境:vs2017、asp.net mvc、jquery-1.10.2.js (專案建立時預設)
以下的範例是透過 vs2017 建立 asp.net mvc 專案 (有預設頁面的那種),建立
之後。
1.先在專案中增加 Json 資料夾
2.再修改 Home/Index.cshtml 的內容而成
使用到的 Json 檔則是放在 Json 資料夾中
testdata.json
- {
- "Key1":"Value1",
- "Key2":"Value2"
- }
然後在 Views\Web.config 中增加新的 mime,如果站台是架在 IIS 上,可以考慮設
定在 IIS 的 mime 上。
- <system.webServer>
- <staticContent>
- <mimeMap fileExtension=".json" mimeType="application/json">
- </staticContent>
- </system.webServer>
最後是頁面上寫讀取 Json 的 ajax
注意要用 GET
- \Home\Index.cshtml
- @{
- Layout = null;
- }
- <html>
- <head>
- <title></title>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script>
- jQuery.ajax({
- url: '/Json/testdata.json',
- type: 'GET',
- success: function (response) {
- alert(JSON.stringify(response));
- alert(response.Key1);
- alert(response.Key2);
- }
- })
- //或是透過 jQuery.getJSON 取得 json
- jQuery.getJSON('/Json/testdata.json',
- function (data) {
- alert(JSON.stringify(data));
- alert(data.Key1);
- alert(data.Key2);
- });
- </script>
- </head>
- <body>
- </body>
- </html>
沒有留言:
張貼留言