简体   繁体   中英

Ajax with node.js

i know some persons asked this question before but i don't understand answers :/ I'm using node.js, and i realy want to use Ajax in it. My code is :

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

My problem is at the line "$.ajax({". The server notice me when a user is coming, it's ok. But when he send a message with a 01 code, node crash and say me :

 $.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)

Sorry if my English isn't good, I'm French and bad at English. :/ Thank you for your help :D

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

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\n",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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM