簡體   English   中英

使用 node.js 的 Ajax

[英]Ajax with node.js

我知道之前有人問過這個問題,但我不明白答案:/我正在使用 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)

對不起,如果我的英語不好,我是法國人,英語不好。 :/ 謝謝你的幫助:D

nodejs執行請求相當容易,根本不必使用$.ajax 您可以使用 npm請求模塊。 $.ajax是為觸發來自瀏覽器的請求而構建的。 但是如果你“真的”想在node上使用$.ajax ,我想你可以通讀這個問題

首先,我們從了解 AJAX 開始,Node.Ajax 是一種基於 xml 的客戶端技術,可以自動更新網頁內容,而無需重新加載頁面。 Node.js 是一種服務器端腳本語言。 為了清楚地說明這一點,我們將創建一個客戶端client.html文件和一個服務器server.js除了安裝 npm 之外,我們還將安裝express中間件和我們將要使用的一些依賴項。 npm install --save express body-parser body-parser-xml

讓我們從編寫server.js文件開始。 該文件將解析發送 AJAX 的 xml 請求。 處理請求正文后,服務器應將響應發送回客戶端。

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

});

接下來,創建client.html文件。 此文件將具有簡單的形式,當提交調用 AJAX 函數時,該函數又將 xml 數據發送到server.js然后等待並處理響應

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

希望本指南對未來有所幫助。 謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM