AJAX를 사용하여 nodejs 서버를 요청한 다음 서버의 응답을 HTML 요소에 주입하려고하는 것처럼 들립니다.
체크 아웃 : http://api.jquery.com/jQuery.getJSON/
여기에 연결하고 다른 호스트의 포트 8080에서 실행중인 노드에서 서버 응답을 검색하고, HTML 요소로 그를 삽입 할 jQuery를 사용하는 예입니다.
노드 :
var http = require('http');
var url = require('url');
http.createServer(function (req, res)
{
//parse the url and query string from the request
var url_parts = url.parse(req.url, true);
//if the callback query parameter is set, we return the string (or object)
if(url_parts.query.callback){
var str = "Hi man";
res.writeHead(200, {'Content-Type':'text/html'});
res.end(url_parsed.query.callback+'("'+str+'")');
//if it's not set, let's return a 404 error
}else{
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404 Error');
}
}).listen(process.env.PORT || 8080);
index.html을
<div id="my-div"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
//getJSON and the callback paramater make us cross-domain capable.
$.getJSON('http://myotherhost.com:8080/?callback=?', function(data){
$("#my-div").html(data);
});
});
</script>
이 방법은 괜찮지 만 내 경우 노드의 ID를 다른 포트를 실행하는 다른 port.Application에서 실행됩니다. 이렇게하면 도메인 간 오류가 발생합니다. – sfk
jQuery의'$ .getJSON'과 교차 도메인 아약스의 콜백 매개 변수를 사용할 수 있습니다. 반영 할 답변을 업데이트했습니다. – ndmweb