简体   繁体   中英

how to grab data within a JSON string

Hi all I am trying to display the words "hello JSON" on my web page but it's displaying the full string { "msg": "Hello JSON." } { "msg": "Hello JSON." } . I know why it is doing that, but how can I get it to display just hello JSON without just plopping it into an html script and using just that?

This is my code:

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);

then message.js or root (in 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>

Try changing body = data; to body = data.msg; in you 'message.js' file. This will lookup the value for the key, msg , in the JSON object and assign the result to the body variable.

edit

In your alertContents function, replace:

alert(httpRequest.responseText);

with:

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

What this does is parse the JSON response into a Javascript object and then looks up the msg attribute and uses that for the alert.

edit 2

Any time that you need to parse JSON, use JSON.parse(jsonString). It will return a native JavaScript object that you can store in a variable and look up attributes on, as in the example above.

I cannot see where you're receiving the msg from but at the place where you receive the JSON string just do this.

var jsonResult = receivedData();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM