【问题标题】:Json output with selfhost c# and read response with javascript使用 selfhost c# 输出 Json 并使用 javascript 读取响应
【发布时间】:2016-07-18 14:02:24
【问题描述】:

我用c#创建了一个简单的selfhost,其中:

public JObject Get()   
{          
    jsonOut = @"{""server"": ""10.0.0.1"" }";
    return JObject.parse(jsonOut);
}

当我尝试在网络浏览器中打开 url http://localhost:2000/api/test 时,正确地看到响应 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 列的数据意外结束

为什么不工作?

谢谢

【问题讨论】:

    标签: javascript c# html json self-host-webapi


    【解决方案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);
                    }
    
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 2015-12-03
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多