Json使用selfhost c#输出,并使用javascript读取响应

Json output with selfhost c# and read response with javascript

本文关键字:javascript 读取 响应 使用 selfhost 输出 Json      更新时间:2023-10-12

我用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);
                }
            });