后台代码编写
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);
}
}
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");
}
})