0

我一直在谷歌上搜索几个小时,以便从我的网站上托管的客户端 js 发布到 nodejs 服务器,而不是将这些结果返回给我的客户端。

这是我想要完成的一个例子:

<html>
<head>
<script type="text/javascript">
var my_id = <?=$myuserid;?>;
$(function(){
    $.ajax({
        url: 'http://mydomain.com:8001/get_friends',
        dataType: 'JSONP',
        type: 'POST',
        crossDomain: true,
        data: {
            id: my_id
        },
        success: function(data){
            if(data.error===true){
                alert(data.msg);
            } else {
                alert(data.users);
            }
        }
    });
});
</script>
</head>
<body>
</body>
</html>

比 NodeJS 文件:

var http = require('http'),
    url = require('url'),
    mysql = require('mysql'),
    sys = require('sys');
var client = mysql.createClient({
    user: 'root',
    password: 'password',
});

http.createServer(function(request, response){
    client.query('USE mydatabase');
    client.query(
        'SELECT * FROM buddy_list WHERE user_id = "This is where I need my post to go"',
        function selectCb(err, results, fields){
            if(err){
                throw err;
            }
            response.writeHead(200, { 'Content-Type' : 'application/json' });
            "Here I need it to feed back results to client script."
            response.end();
            client.end();
    })
}).listen(8001);
4

2 回答 2

3

抛开输入卫生问题不谈,以下是解决此问题的方法:

http.createServer(function(request, response){
    request.on('data', function(chunk) {
        dataInput = chunk.toString();
        client.query('USE mydatabase');
        client.query(
            'SELECT * FROM buddy_list WHERE user_id = ' + dataInput,
            function selectCb(err, results, fields){
                if(err){
                    throw err;
                }
                response.writeHead(200, { 'Content-Type' : 'application/json' });
                "Here I need it to feed back results to client script."
                response.end();
                client.end();
        })

    })
}).listen(8001);
于 2011-10-07T03:37:40.520 回答
1
response.writeHead(200, { 'Content-Type' : 'application/json' });
response.send( JSON.stringify(results) );

我还没有尝试过,但它看起来像你想要的。我不确定有什么结果、字段或者是否需要更多的数据操作。我假设“结果”是一个 JSON 对象。

于 2011-10-07T04:21:15.277 回答