2014-02-07 5 views
1

안녕하세요. 내 웹 페이지에 "hello JSON"이라는 단어를 표시하려하지만 전체 문자열 { "msg": "Hello JSON." }이 표시됩니다. 나는 왜 그런 일을하는지 알지만, 단지 hello JSON을 html 스크립트에 뿌리고 그냥 사용하지 않고 표시 할 수 있습니까? JSON 문자열 내에서 데이터를 가져 오는 방법

내 코드입니다 :

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

다음 분 VAR 루트 =에 message.js 또는 루트 ((필요/메시지)

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> 
+0

출처가 어디에서라도 json을 디코딩하지 않는 것 같습니다. 기억하세요, json은 텍스트 일뿐입니다. 모 놀리 식 문자열이 아닌 다른 것으로 실제로 사용할 수 있으려면 네이티브 JS 구조로 다시 디코딩해야합니다. –

+0

js 구조로 다시 디코딩한다는 것은 무엇을 의미합니까? 내가 어떻게 할 수 있니? JSON.parse로 무언가를하려고했지만 개별 부분을 잡을 수는 없습니다. –

답변

2

'message.js'파일에서 body = data;body = data.msg;으로 변경해보십시오. 그러면 키 값인이 조회됩니다.을 JSON 객체에 저장하고 결과를 body 변수에 지정합니다.

편집 당신의 alertContents 기능에

은 대체 :

alert(httpRequest.responseText); 

로 :이 무엇

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

는 자바 스크립트 객체에 JSON 응답을 구문 분석하고 다음 찾습니다 msg 속성을 사용하고 경고에 해당 속성을 사용합니다.

편집이

당신이 JSON을 구문 분석 할 때마다, JSON.parse (jsonString)를 사용합니다. 위 예제에서와 같이 변수에 저장하고 속성을 찾을 수있는 네이티브 JavaScript 객체를 반환합니다.

+0

서버 오류가 표시된다. 실제로 .init을 호출하지 않는다. –

+0

데이터를 인쇄 할 때마다 '.msg'를 추가하여 전체 JSON 객체가 아닌 메시지 만 출력한다. – ki4jnq

+0

res.end (body) 내가 res.end (body.msg)라고 할 수 있을까요? 페이지를로드하지 않기 때문에 무한 루프 나 무언가에 넣을 수 있습니다. var resDataString = httpRequest.responseText; var resData = JSON.parse (resDataString); var msg = resData.msg; //하지만 idk 어디에 배치 할까 –

0

메시지 수신 위치를 확인할 수 없지만 JSON 문자열을 수신 한 곳에서 확인할 수 있습니다.

var jsonResult = receivedData(); 

if (jsonResult && jsonResult.msg) 
{ 
    alert(jsonResult.msg);} 
} 
관련 문제