如何使用与node.js的jQuery的Ajax调用 [英] how to use jQuery ajax calls with node.js

查看:108
本文介绍了如何使用与node.js的jQuery的Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是类似于流数据与Node.js的的,但我不'牛逼觉得这个问题充分回答。

我尝试使用jQuery的AJAX调用(得到,负载的getJSON)到一个页面,使Node.js服务器之间传输数据。我可以从我的浏览器中点击地址,看到Hello World的,但是当我尝试这从我的网页,它失败并表明我没有得到任何答复后,我设置了一个简单的测试页面,Hello World示例来测试这个!:

 <!DOCTYPE HTML>
< HTML LANG =EN>
< HEAD>
    <元字符集=utf-8/>
    <冠军>获得测试< /标题>
< /头>
<身体GT;
    < H1>获取测试和LT; / H1>
    < D​​IV ID =测试>< / DIV>

    &LT;脚本的src =// ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    &LT;脚本&GT;
        $(文件)。就绪(函数(){
            //alert($('h1').length);
            $('#检测').load('http://192.168.1.103:8124/');
            //$.get('http://192.168.1.103:8124/',功能(数据){
            //警报(数据);
            //});
        });
    &LT; / SCRIPT&GT;
&LT; /身体GT;
&LT; / HTML&GT;
 

  VAR HTTP =需要('HTTP');

http.createServer(功能(REQ,RES){
    的console.log('请求接受');
    res.writeHead(200,{内容类型:text / plain的'});
    res.end(你好世界\ N');
})听(8124);
 

解决方案

如果您简单的测试页是否位于其他协议/域/端口比你的Hello World Node.js的例子中,你正在做跨域请求,违反<一HREF =htt​​p://en.wikipedia.org/wiki/Same_origin_policy>同源策略因此您的jQuery Ajax调用(get和负载)都默默地失败。得到这个工作跨域你应该使用 JSONP 的基础格式。例如Node.js的code:

  VAR HTTP =需要('HTTP');

http.createServer(功能(REQ,RES){
    的console.log('请求接受');
    res.writeHead(200,{内容类型:text / plain的'});
    res.end('_ testcb(\'{消息:世界,你好} \')');
})听(8124);
 

和客户端的JavaScript / jQuery的:

  $(文件)。就绪(函数(){
    $阿贾克斯({
        网址:http://192.168.1.103:8124/,
        数据类型:JSONP
        jsonpCallback:_testcb
        缓存:假的,
        超时:5000,
        成功:功能(数据){
            $(#考)追加(数据);
        },
        错误:函数(jqXHR,textStatus,errorThrown){
            警报('错误'+ textStatus ++ errorThrown);
        }
    });
});
 

此外,还有其他的方法如何通过设置反向代理或构建Web应用程序得到这个工作,例如完全用框架,比如 EX preSS

This is similar to Stream data with Node.js, but I don't feel that question was answered sufficiently.

I'm trying to use a jQuery ajax call (get, load, getJSON) to transfer data between a page and a node.js server. I can hit the address from my browser and see 'Hello World!", but when I try this from my page, it fails and shows that I get no response back. I setup a simple test page and hello world example to test this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>get test</title> 
</head>
<body>
    <h1>Get Test</h1>
    <div id="test"></div>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script>
        $(document).ready(function() {
            //alert($('h1').length);
            $('#test').load('http://192.168.1.103:8124/');
            //$.get('http://192.168.1.103:8124/', function(data) {                
            //  alert(data);
            //});
        });
    </script>
</body>
</html>

and

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(8124);

解决方案

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:

var http = require('http');

http.createServer(function (req, res) {
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);

and client side JavaScript/jQuery:

$(document).ready(function() {
    $.ajax({
        url: 'http://192.168.1.103:8124/',
        dataType: "jsonp",
        jsonpCallback: "_testcb",
        cache: false,
        timeout: 5000,
        success: function(data) {
            $("#test").append(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('error ' + textStatus + " " + errorThrown);
        }
    });
});

There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.

这篇关于如何使用与node.js的jQuery的Ajax调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆