开发者

Post to nodejs and return results

开发者 https://www.devze.com 2023-04-11 02:54 出处:网络
I have been searching for hours on google for away to post from my client js hosted on my site to a nodejs server, than return those results back to my client side.

I have been searching for hours on google for away to post from my client js hosted on my site to a nodejs server, than return those results back to my client side.

This is an example of what I'm trying to accomplish:

<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>

Than the NodeJS File:

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){
       开发者_如何学C     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);


Input sanitation issues aside, here is how you would solve this:

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);


response.writeHead(200, { 'Content-Type' : 'application/json' });
response.send( JSON.stringify(results) );

I have not tried this but it looks like what you want. I'm not sure what results, fields have or if there needs to be more data manipulation. I'm assuming "results" is a JSON object.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号