jquery - Correct Approach for Serving Javascript Files via Node.js Ajax? -
jquery - Correct Approach for Serving Javascript Files via Node.js Ajax? -
i trying write node application serves crjavascript code static webpage. code evaluated in webpage. similar this example, node instead of php. server application looks this:
// load http module create http server. var http = require('http'); // configure our http server var server = http.createserver(function (req, res) { var js; //send libraries fs = require('fs'); res.writehead(200, {'content-type': 'text/plain'}); //var paths = ['javascript.js']; js = fs.readfilesync('example.js').tostring(); res.end('_js(\'{"message": " ' + js + '"}\')'); }); // hear on port 8000, ip defaults 127.0.0.1 server.listen(8000); // set message on terminal console.log("server running @ http://127.0.0.1:8000/");
while client code looks this:
<html> <head> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" charset="utf-8"/> <script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: 'http://127.0.0.1:8000/', datatype: "jsonp", jsonpcallback: "_js", cache: false, timeout: 20000, success: function(data) { var datajson = json.parse(data); console.log(datajson['message']); eval(datajson['message']); alert(test); }, error: function(jqxhr, textstatus, errorthrown) { console.log('error ' + textstatus + " " + errorthrown); } }); }); </script> </head> <body> <div class="container" id="container"></div> </body> </html>
example.js contains 1 line alert('hello world')
. thought send line of code index.html using ajax query , run it. however, maintain getting errors based on line because of ungainly mess of apostrophes , brackets:
res.end('_js(\'{"message": " ' + js + '"}\')');
i thinking there must improve way this?
if don't have hard requirement serve javascript via ajax, much simpler utilize node based web-server, such expressjs, allows serve static content.
javascript jquery node.js
Comments
Post a Comment