旧行李
2015-01-24 10:41
采纳率: 25%
浏览 313

如何在node.js中使用Ajax?

我知道以前有人问过这个问题,但我还是不明白。我正在使用node.js,还想在其中使用Ajax。我的代码是:

var $ = require('jquery');
var http = require("http");
var ws = require("nodejs-websocket");
var fs = require("fs");
var colors = require('colors');

http.createServer(function (req, res) {
    fs.createReadStream("index.php").pipe(res)
}).listen(8080)
// ###################################################################################################################################
// ########################################################## CLASSE SERVER ##########################################################
// ###################################################################################################################################
var tableauDeJoueur = new Array();

var server = ws.createServer(function (connection){
    connection.nickname = null
    connection.on("text", function (str){
        if (connection.nickname === null){
            connection.nickname = str;
            
            console.log((connection.nickname+" arrive sur PixelWorld !").green);
        }
        else{
            var code = str.substring(0,2);
            var reste = str.substring(2,str.length);
            switch(code){
                case "01":
                    var coupe = reste.split("4H[m~Ft7");
                    var mail = coupe[0];
                    var mdp = coupe[1];
                    $.ajax({
                        url: "fonctionPHP/connection.php",              
                        type: "POST",
                        data: {'mail': mail,'mdp': mdp},
                        async:false,
                        success: function(html){
                            if(html == "OK"){
                                console.log("oui");
                            }
                            else{
                                console.log("non");
                            }
                        }
                    });
                    break;
                case "02":
                    break;
            }
        }
    })
    connection.on("close", function (){
        console.log((connection.nickname+" a quitté PixelWorld !").red);
    })
})
server.listen(8081)

function broadcast(str) {
    server.connections.forEach(function (connection) {
        connection.sendText(str)
    })
}

我的问题是在“ $ .ajax({”这里。当用户到来时,服务器会通知我,这没关系。但是,当它发送带有01代码的消息时,节点会崩溃并提示:

 $.ajax({
                                          ^
TypeError: Object function ( w ) {
                                if ( !w.document ) {
                                        throw new Error( "jQuery requires a window with a document" );
                                }
                                return factory( w );
                        } has no method 'ajax'
    at Connection.<anonymous> (/var/www/dhkuhnuhbnkiuh/app.js:46:8)
    at Connection.EventEmitter.emit (events.js:95:17)
    at Connection.processFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:516:9)
    at Connection.extractFrame (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:458:14)
    at Connection.doRead (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:209:23)
    at Socket.<anonymous> (/var/www/dhkuhnuhbnkiuh/node_modules/nodejs-websocket/Connection.js:52:8)
    at Socket.EventEmitter.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:408:10)
    at emitReadable (_stream_readable.js:404:5)
    at readableAddChunk (_stream_readable.js:165:9)

感谢你的帮助!

</div>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_33729196 2015-01-24 10:51

    Doing a request from nodejs is fairly easy, dont have to use $.ajax at all. You can use the npm request module. $.ajax is built for firing requests from the browser. But if you 'really' want to use $.ajax on node, I think you can read through this question

    点赞 评论
  • weixin_33717298 2017-01-24 21:10

    First,we begin with understanding AJAX and Node.Ajax is a client-side xml-based technology that automatically updates contents of a web page, without the page having to reload. Node.js is a server-side scripting language. To illustrate this clearly, we will create a client client.html file and a server server.js Aside from having npm installed, we will install express middleware and some of it's dependencies that we are going to use. npm install --save express body-parser body-parser-xml

    Let's begin by writing our server.js file. This file is going to parse xml requests sent AJAX. After processing request body, server should then send response back to client.

    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    require('body-parser-xml')(bodyParser);
    app.use(bodyParser.xml({
    limit:'1MB',
    XmlParseOptions:{
    normalize:true,
    normalizeTags:true,
    explicitArray:false
    }
    }));
    app.get('/',function(req,res){
    res.sendFile(__dirname + "/" + "client.html");
    });
     app.post('/library',bodyParser.urlencoded({extended:false}),function(req,res){
    console.log(req.body);
    var title = req.body.book.title;
    var author = req.body.book.author;
    var year = req.body.book.year;
    console.log(title + " " +author + " " +year);
    //optional operations like database can be performed here
    // we are sending a response mimicking a successfull search query
    res.end("Book Found in library");
    })
    var server = app.listen(8080,function(){
    var host = '127.0.0.1';
    var port = server.address().port;
    console.log("Server running at http://%s:%s
    ",host,port);
    

    });

    Next, create client.html file. This file will have simple form that when submitted call on an AJAX function that in turn sends xml data to server.js then waits and process response

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <script type = "text/javascript">
    function Search() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.getAllResponseHeaders();
    xmlhttp.open('POST','http://127.0.0.1:8080/library',true);
    console.log(document.getElementById('title').value);
    console.log(document.getElementById('author').value);
    var text = "<book>" +
    "<title>"+document.getElementById('title').value+"</title>" +
    "<author>"+document.getElementById('author').value+"</author>" +
    "<year>"+document.getElementById('year').value+"</year>" +
    "</book>";
    xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4){
    if(xmlhttp.status == 200){
    alert(xmlhttp.responseText);
    console.log("All ok. You hit the server");
    }
    }
    };
    xmlhttp.setRequestHeader("Content-Type","text/xml");
    xmlhttp.send(text);
    }
    </script>
    </head>
    <body>
    <form name = "" method = "POST" action = "">
    Title:<input type = "text" name = "title" id = "title">
    Author:<input type = "text" name = "author" id = "author">
    Year:<input type = "text" name = "year" id = "year"><br>
    <br>
    <input type = "button" value = "Search" onclick = "Search()"/>
    </form>
    </body>
    </html>
    

    Hope this guide helps in future. Thanks

    点赞 评论

相关推荐 更多相似问题