如何在JSON字符串中获取数据

时间:2014-02-07 02:09:22

标签: javascript json node.js

大家好我想在我的网页上显示单词"hello JSON",但它显示完整的字符串{ "msg": "Hello JSON." }。我知道为什么会这样做,但我怎么能让它只显示hello JSON而不仅仅是将它放入一个html脚本并使用它?

这是我的代码:

var http = require('http');
var domain = require('domain');
var root = require('./message'); // do I have to replace root w/ message 
var image = require('./image');  // for better readability?

function replyError(res) {
  try {
    res.writeHead(500);
    res.end('Server error.');
  } catch (err) {
    console.error('Error sending response with code 500.');
  }
};

function replyNotFound(res) {
  res.writeHead(404);
  res.end('not found');
}

function handleRequest(req, res) {
  console.log('Handling request for ' + req.url);
  if (req.url === '/') {
    root.handle(req, res);  
  }

  if (req.url === '/image.png'){
    image.handle(req, res);
  } else {
    replyNotFound(res);
  }
}

var server = http.createServer();

server.on('request', function(req, res) {
  var d = domain.create();
  d.on('error', function(err) {
    console.error(req.url, err.message);
    replyError(res);
  });

  d.run(function() { handleRequest(req, res)});
});


    server.listen(5000);

然后是message.js或root(在min var root = require(/ message)

var http = require('http');
var body;

exports.handle = function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Content-Length': body.length
});
  res.end(body);
};

exports.init = function(cb) {
  require('fs').readFile('app.html', function(err, data) {
    if (err) throw err;
    body = data;
    cb();
  });
}

app.html

 <html>

<header><title>This is title</title></header>

<body>

Hello world



<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">

  Make a request

</span>

<script type="text/javascript">

(function() {

  var httpRequest;

  document.getElementById("ajaxButton").onclick = function() { makeRequest('message.js'); };

  function makeRequest(url) {

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();

    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");

      } 

      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;

    }

    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', url);
    httpRequest.send(msg);

  }

  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {

        alert(httpRequest.responseText);

      } else {
        alert('There was a problem with the request.');
      }
    }
  } 
})();
 </script>
</body> 
</html>

2 个答案:

答案 0 :(得分:2)

尝试将“message.js”文件中的body = data;更改为body = data.msg;。这将在JSON对象中查找键msg的值,并将结果分配给主体变量。

修改

alertContents功能中,替换:

alert(httpRequest.responseText);

使用:

var resData = JSON.parse(httpRequest.ResponseText);
alert(resData.msg);

这样做是将JSON响应解析为Javascript对象,然后查找msg属性并将其用于警报。

编辑2

任何时候需要解析JSON,请使用JSON.parse(jsonString)。它将返回一个本机JavaScript对象,您可以将其存储在变量中并查找属性,如上例所示。

答案 1 :(得分:0)

我无法看到你从哪里收到消息,但在你收到JSON字符串的地方只是这样做。

var jsonResult = receivedData();

if (jsonResult && jsonResult.msg)
{
  alert(jsonResult.msg);}
}