首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

jquery与nodejs直接ajax交互

2013-04-20 
【求助】jquery与nodejs直接ajax交互对网络技术不是很了解,是我们的课程作业。望高人指点。我就是想用前台的jq

【求助】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>


这个是nodejs端的代码
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/');


看node.js command prompt 上面显示的log信息,应该是成功发送了请求,但是我不知道如何从nodejs端把数据回传到html端。html页面一直打印错误信息。求指点!还有我就是从网上下了个nodejs的windows版本,然后安装了一下,这样是不是就够了?还需要配置什么环境么? ajax jquery nodejs
------解决方案--------------------


访问http://127.0.0.1:1337/这个有输出没有,没有就是node.js没配置好,和jquery没什么关系

看你的输出应该使用的是jsonp,不要注释掉dataType:'jsonp'

$(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.');
        },
    });
});

热点排行