2015-01-24 5 views
0

어떤 사람들은 전에이 질문을했지만 대답을 이해할 수 없다는 것을 알고 있습니다 :/ node.js를 사용하고 있으며 실제로 Ajax를 사용하고 싶습니다. 내 코드는 다음과 같습니다..Ajax with node.js

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) { 
 
\t fs.createReadStream("index.php").pipe(res) 
 
}).listen(8080) 
 
// ################################################################################################################################### 
 
// ########################################################## CLASSE SERVER ########################################################## 
 
// ################################################################################################################################### 
 
var tableauDeJoueur = new Array(); 
 

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

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

내 문제는 줄에서 "$ 아약스 ({" 서버는 사용자가오고 나를 통지, 그것의입니다 확인 그러나 그는 보낼 때 A A 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)

죄송합니다. 영어 실력이 좋지 않으면 프랑스어이고 영어 실력이 떨어집니다. :/ 당신의 도움에 감사드립니다 :

+0

다음을 참조하십시오. https://github.com/UncoolAJ86/node-jquery가 도움이 될 수 있습니다. – Hacketo

답변

1

nodejs의 요청은 매우 쉽습니다. $.ajax을 전혀 사용하지 않아도됩니다. npm request 모듈을 사용할 수 있습니다. $.ajax은 브라우저에서 요청을 실행하기 위해 만들어졌습니다. 당신은 '정말'node$.ajax을 사용하려는 경우, 나는, 우리가 이해 AJAX와 Node.Ajax로 시작 this question

+0

그래서 "이해"하면 아약스가 필요 없다고 말합니다. "요청"이 필요한 것을 할 수 있기 때문입니다. 나 맞아? –

+0

예! 서버 측 코드에서 JQuery를 사용할 필요가 없다. 주로 DOM 조작을 위해 제작되었으며 브라우저 측 UI 작업을 쉽게 만든다. npm 패키지'request'는 필요한 기능을 제공합니다. – surajck

+0

정말 고마워요! 프로젝트를 닫아야합니까? 이 웹 사이트에서 어떻게 감사 할 수 있습니까? –

0

첫째 통해 읽을 수 자동으로 내용을 업데이트하는 클라이언트 측 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 + "/" + "stackclient.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 파일을 생성한다. 이 파일은 다시 다음 server.js에 XML 데이터를 전송 대기 AJAX 기능 및 프로세스 응답

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

희망에 전화를 제출하면이 가이드는 미래에 도움이 간단한 양식이있을 것이다. 감사합니다