MVC读取JSON文件

xiaoxiao2021-02-27  229

后台代码编写


//json文件路径:"~/Content/json/XXX.json" public ActionResult GetJsonFromFile(string path) { try { string filepath = Server.MapPath(path); string json = GetFileJson(filepath); return Content(json); } catch (Exception ex) { return Content(ex.Message); } } //具体读取json文件数据 public string GetFileJson(string filepath) { string json = string.Empty; using (FileStream fs = new FileStream(filepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312"))) { json = sr.ReadToEnd().ToString(); } } return json; }

前台页面调用


$.ajax({ url: "/ControlName/GetJsonFromFile", type: "GET",//请求方式为get dataType: "json", //返回数据格式为json data: { path: "~/Content/json/XXX.json" }, async: false,//是否同步 success: function (data) {//请求成功完成后要执行的方法 //dosometing.... }, error: function () { console.log("error"); } })
转载请注明原文地址: https://www.6miu.com/read-8874.html

最新回复(0)