Javascript 如何从httplistener中的.json文件加载数据
我是WebService/JavaScript开发环境的新手。我得到了一个当前任务,我们的HttpListener代码为.js文件的localhost请求提供服务。我需要的是能够在HttpListener中放置json对象Javascript 如何从httplistener中的.json文件加载数据,javascript,json,httplistener,Javascript,Json,Httplistener,我是WebService/JavaScript开发环境的新手。我得到了一个当前任务,我们的HttpListener代码为.js文件的localhost请求提供服务。我需要的是能够在HttpListener中放置json对象 从JSON文件(.JSON)接收值类型、对象和列表(或数组),并将JSON字符串转换为JavaScript对象 将值类型、对象和列表发送到JavaScript 将上述json数据输出到控制台 如果你能分享一些想法/解决方案来实现这一点,那就太好了 下面是我们当前使用.js
- 从JSON文件(.JSON)接收值类型、对象和列表(或数组),并将JSON字符串转换为JavaScript对象
- 将值类型、对象和列表发送到JavaScript
- 将上述json数据输出到控制台
private static void Main()
{
var server = new HttpListener();
server.Prefixes.Add("http://localhost:80/");
server.Start();
Console.WriteLine("Listening...");
while (true)
{
HttpListenerContext context = server.GetContext();
HttpListenerResponse response = context.Response;
string fileId = string.Empty;
try
{
string page = Path.Combine(Directory.GetCurrentDirectory(), context.Request.Url.LocalPath.Replace("/", @"\").Substring(1));
Console.WriteLine("Get request from {0}", page);
if (!string.IsNullOrEmpty(page) && !page.EndsWith(".js"))
{
Console.WriteLine("file is not a .js file.");
continue;
}
// Check requested file really exists
// Get file id property from the query string.
fileId = context.Request.QueryString["fileid"];
string msg;
using (var sr = new StreamReader(page))
{
msg = sr.ReadToEnd();
}
byte[] buffer = Encoding.UTF8.GetBytes(msg);
response.ContentLength64 = buffer.Length;
response.ContentType = "text/javascript";
using (Stream st = response.OutputStream)
{
Console.WriteLine(buffer.Length);
st.Write(buffer, 0, buffer.Length);
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.StatusDescription = "OK";
Console.WriteLine("Request done:{0}", fileId);
}
catch { } // suppress any exceptions
finally
{
context.Response.Close();
Console.WriteLine("Response closed:{0}", fileId);
}
}
}
Data.json的示例。但我们不知道会出现什么字段名和数据类型
[
{
"name": "George",
"gender": "male",
"age": "5 years"
},
{
"name": "Nancy",
"gender": "female",
"age": "10 years"
},
{
"name": "Alex",
"gender": "male",
"age": "3 years"
},
{
"name": "Maximus",
"gender": "male",
"age": "7 years"
}
]