【求助】jquery与nodejs直接ajax交互
对网络技术不是很了解,是我们的课程作业。望高人指点。
我就是想用前台的jquery想后台发送请求,并从nodejs端返回值到前台(html)。乱试了不少代码,可是怎么样都回传不了数据。我从网上下了一串代码。可是一直说连接有错。求指点,如何能让jquery和nodejs交互成功?作业得处理从nodejs返回到html的结果。
这个是html文件的代码,jquery.js用的是这个链接的:http://code.jquery.com/jquery-1.9.1.js。
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
response here: <p id="lblResponse">fill me in</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:1337/',
// dataType: "jsonp",
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});
</script>
</body>
</html>
var http = require('http');
var util = require('util')
http.createServer(function (req, res) {
console.log('Request received: ');
util.log(util.inspect(req)) // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST)
util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) // this line logs just the method and url
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('callback(\'{"msg": "OK"}\')');
}).listen(1337,'127.0.0.1');
console.log('Server running on port http://127.0.0.1:1337/');
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:1337/',
dataType: "jsonp",////////
data: '{"data": "TEST"}',
type: 'POST',
jsonpCallback: 'callback', // this is not relevant to the POST anymore
success: function (data) {
var ret = jQuery.parseJSON(data);
$('#lblResponse').html(ret.msg);
console.log('Success: ')
},
error: function (xhr, status, error) {
console.log('Error: ' + error.message);
$('#lblResponse').html('Error connecting to the server.');
},
});
});