【求助】jquery与nodejs直接ajax交互

hunter12345654 2013-04-02 04:08:37
对网络技术不是很了解,是我们的课程作业。望高人指点。
我就是想用前台的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版本,然后安装了一下,这样是不是就够了?还需要配置什么环境么?
...全文
6733 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
郭靖丶 2013-06-14
  • 打赏
  • 举报
回复
同源策略限制了跨域访问.你nodejs服务器端口和你ajax的端口不同,所以被认为是跨域访问.解决方案有很多,比方说代理,或者express里面进行设置.代理的具体设置方式可以百度一下.很多成功案例的. 下面是express的解决方案.

var express = require('express');
var app = express();
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/auth/:id/:password', function(req, res) {
    res.send({id:req.params.id, name: req.params.password});
});

app.listen(3000);
console.log('Listening on port 3000...');
在跨域状态下,jquery会转换为get请求,解决了跨域问题,就不会自动转换了.
hunter12345654 2013-04-11
  • 打赏
  • 举报
回复
引用 3 楼 showbo 的回复:
你没有跨域吧。。 高版本的jquery,好像是1.5+以上的,跨域后jsonp会自动转为get请求,没跨域就是post jquery1.5之下的,post请求跨域页面没反应,只能get请求跨域的才会执行回调
我不太懂。。。那我如何能做到都是post的方法呢?谢谢!
Go 旅城通票 2013-04-03
  • 打赏
  • 举报
回复
你没有跨域吧。。 高版本的jquery,好像是1.5+以上的,跨域后jsonp会自动转为get请求,没跨域就是post jquery1.5之下的,post请求跨域页面没反应,只能get请求跨域的才会执行回调
hunter12345654 2013-04-03
  • 打赏
  • 举报
回复
引用 1 楼 showbo 的回复:
访问http://127.0.0.1:1337/这个有输出没有,没有就是node.js没配置好,和jquery没什么关系 看你的输出应该使用的是jsonp,不要注释掉dataType:'jsonp' JavaScript code?123456789101112131415161718$(document).ready(function() { $.aj……
如果只是访问http://127.0.0.1:1337/时是有输出结果的。 弄成功了,可以回传值了。谢谢! 不过我有个问题想问问,jquery里面写的type是“POST”的,但是服务器端打印出来的结果的最后几行显示的是“GET”方法?
2 Apr 12:30:33 - Request recieved:
method: GET
url: /?hello=nihao&callback=callback&{%22data%22:%20%22TEST%22,%22nani%22:%20%22
no%20way%22}&_=1364931033077
{ hello: 'nihao',
  callback: 'callback',
  '{"data": "TEST","nani": "no way"}': '',
  _: '1364931033077' }
Go 旅城通票 2013-04-02
  • 打赏
  • 举报
回复
访问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.');
        },
    });
});

52,797

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ajax
社区管理员
  • Ajax
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧