Json使用selfhost c#输出,并使用javascript读取响应
Json output with selfhost c# and read response with javascript
我用c#创建一个简单的自主机,其中:
public JObject Get()
{
jsonOut = @"{""server"": ""10.0.0.1"" }";
return JObject.parse(jsonOut);
}
当我尝试打开url时http://localhost:2000/api/test进入web浏览器,正确地看到响应json:{"server":"10.0.0.1"}。在我创建一个网页后:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtdlocalhost">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<meta name="description" content="Portale per Webmaster">
<meta name="keywords" content="HTML,CSS,JavaScript,PHP,ASP">
<meta http-equiv="refresh" content="900">
<script type="text/JavaScript">
function ajaxRequest() {
var xmlhttp = new XMLHttpRequest();
var url = "http://10.1.3.62:2000/api/test";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json=eval("("+xmlhttp.responseText+")");
document.getElementById("info").innerHTML = json.server;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
window.onLoad = ajaxRequest();
setInterval(ajaxRequest, 2000);
</script>
</head>
<body>
<div id="info"></div>
</body>
</html>
但我没有看到任何变化,在firefox的开发工具中出现了以下错误:
SyntaxError:JSON.parse:JSON数据第1行第1列的数据意外结束
为什么不起作用?
感谢
我的建议是使用AJAX来读取JSON格式,我重写代码如下:
var senderData = { id: "1" }
$.ajax({
type: "POST",
url: "http://10.1.3.62:2000/api/test",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(senderData),
success: function (response) {
var items = eval(response.d);
},
error: function (error) {
console.log(error);
}
});
相关文章:
- 使用Dnamics CRM 2011中的JavaScript读取子网格的所有记录,而不考虑活动页面
- 通过传递图像的URL通过javascript读取/处理图像-类似于PHP中的file_get_contents
- 使用Javascript读取Webstorage表单数据
- 函数式javascript读取、异步、写入结果
- 使用Javascript读取CSS文件并动态更改页面
- 使用javascript读取和写入json文件
- 正在以javascript读取本地csv文件
- 用javascript读取文本文件的第一行
- 使用javascript读取本地XML文件并在html页面中显示
- 使用Javascript读取当前目录的文件名
- 从JavaScript读取动态内容
- 使用 javascript 读取.txt文件
- 使用 Javascript 读取目录的内容
- 使用 c# 编写 cookie,使用 javascript 读取
- 获取由 javascript 读取的数组文本字段值
- 使用 Javascript 读取文本文件
- 使用javascript读取文件
- 使用jQuery或JavaScript读取属性文件
- Json通过Javascript读取数据
- Javascript-读取文本框长度