2018年6月5日 星期二

[jQuery]利用 jQuery.ajax 讀取 Json 檔案

利用 jQuery.ajax 讀取 Json 檔案

環境:vs2017、asp.net mvc、jquery-1.10.2.js (專案建立時預設)

以下的範例是透過 vs2017 建立 asp.net mvc 專案 (有預設頁面的那種),建立
之後。

1.先在專案中增加 Json 資料夾
2.再修改 Home/Index.cshtml 的內容而成

使用到的 Json 檔則是放在 Json 資料夾中

testdata.json

  1. {
  2. "Key1":"Value1",
  3. "Key2":"Value2"
  4. }

然後在 Views\Web.config 中增加新的 mime,如果站台是架在 IIS 上,可以考慮設
定在 IIS 的 mime 上。

  1. <system.webServer>
  2. <staticContent>
  3. <mimeMap fileExtension=".json" mimeType="application/json">
  4. </staticContent>
  5. </system.webServer>

最後是頁面上寫讀取 Json 的 ajax

注意要用 GET

  1. \Home\Index.cshtml
  2.  
  3. @{
  4. Layout = null;
  5. }
  6.  
  7. <html>
  8. <head>
  9. <title></title>
  10. <script src="~/Scripts/jquery-1.10.2.min.js"></script>
  11. <script>
  12. jQuery.ajax({
  13. url: '/Json/testdata.json',
  14. type: 'GET',
  15. success: function (response) {
  16. alert(JSON.stringify(response));
  17. alert(response.Key1);
  18. alert(response.Key2);
  19. }
  20. })
  21. //或是透過 jQuery.getJSON 取得 json
  22. jQuery.getJSON('/Json/testdata.json',
  23. function (data) {
  24. alert(JSON.stringify(data));
  25. alert(data.Key1);
  26. alert(data.Key2);
  27. });
  28. </script>
  29. </head>
  30. <body>
  31. </body>
  32. </html>

沒有留言:

張貼留言