【问题标题】:Why I'm getting pure json data which can't be displayed为什么我得到无法显示的纯 json 数据
【发布时间】:2015-11-19 04:18:17
【问题描述】:

我正在尝试构建一个具有 2 个功能的简单网络: 1. 从服务器获取字符串(短信)消息,并显示在屏幕上 2. 发送(发布)表单数据到服务器,服务器发回数据,这些数据将被记录。

服务器代码:

app.get('/sms', function (req, res) {   
   var smsMsg = fs.readFileSync('sms.txt');
   console.log('Read File: ' + smsMsg.toString());
   res.send(smsMsg.toString());   
})

app.post('/result', function (req, res) {      
   console.log('Got Personal Information: ' + req.body.firstName + " " + req.body.lastName);   

   response = {
       first_name:req.body.firstName,
       last_name:req.body.lastName,
       id:'0399'
   };
   console.log(response);

   // value to a JSON string 
   res.setHeader('Content-Type', 'application/json');  
   res.send(JSON.stringify(response));
})

客户端代码:

<body>      

     <p>    
        <button onclick="sendRequestForSms()"> Get SMS From Server </button>
        </br>
        <h1 id="smsId"> SMS: <h1>
        </br>
     </p>
     <p>
        <form action="/result" method="post">       
            <fieldset>
                <legend>Personal information:</legend>
                 First name: 
                <input type="text" name="firstName">
                <br>
                Last name:
                <input type="text" name="lastName">
                <br>
                <input type="submit" value="Submit" id="submit">
            </fieldset>
        </form> 
     </p>

    <script type="text/javascript">


            var xmlhttp;
            if (window.XMLHttpRequest) 
            {
                xmlhttp = new XMLHttpRequest();
            }
            else 
            {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.onreadystatechange = function() 
            {       
                  console.log('State: ' + xmlhttp.readyState + ' status: ' + xmlhttp.status);           
                  // 1: server connection established
                  // 4: request finished and response is ready
                  // 200: "OK"
                  // 404: Page not found
                  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
                  {
                        if (xmlhttp.getResponseHeader('Content-Type') == 'application/json') 
                        {
                            console.log('Got Json');
                            var myArr = JSON.parse(xmlhttp.responseText);
                            console.log(myArr);
                        }
                        else
                        {
                            document.getElementById("smsId").innerHTML = xmlhttp.responseText;  
                        }   


                  }
            };

            function sendRequestForSms() {              
                xmlhttp.open("GET", "/sms", true);
                xmlhttp.send();     
            }                                       
        </script>

</body>
  • 当用户点击“从服务器获取 SMS”时,我会得到结果并将其显示在相关元素 ('smsId') 上。

  • 但是 :( 当用户提交表单时,我会得到带有 json 数据的新页面(例如:'{"first_name":"test1","last_name":"test2","id" :"0399"}') 所以我的客户端代码行:console.log('Got Json'); 没有到达,为什么没有调用客户端回调函数?

我做错了什么?

【问题讨论】:

  • 您没有任何代码来处理它,因此浏览器会发布表单并正常加载结果。
  • 服务器打印Got Personal Information?

标签: javascript json ajax node.js


【解决方案1】:

Got Json 永远不会被打印,因为/result(服务器)当前设置为仅回显它发送的 JSON。看起来它正在从表单发送正确的信息,但是您现在设置它的方式“Got Json”只会从您的“获取短信”按钮打印。要按照您尝试执行的方式执行您想要执行的操作,您需要使/result 输出一个新页面,该页面打印出您提交后要运行的javascript。那有意义吗?我可以澄清一下。

XMLHTTPRequest的使用示例

<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/json/myTutorials.txt";

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var myArr = JSON.parse(xmlhttp.responseText);
        myFunction(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + 
        arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>

来源:http://www.w3schools.com/json/json_http.asp

实时示例:http://www.w3schools.com/json/tryit.asp?filename=tryjson_http

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-12
    • 2017-01-04
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多