2017-04-11 150 views
0

我有一個具有輸入數據的ajax get請求。我想將這些數據傳遞給一個變量並在我的查詢中使用它。將ajax值傳遞給node.js服務器中的變量

index.handlebars

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title></title> 
    </head> 
    <body> 
     <input type="hidden" class="test" name="test" value="sample"/> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       var username = $('.test').val(); 
       $.ajax({ 
        type : 'GET', 
        url: '/users//welcome', 
        data : { 
         wew: username 
        } 
       }); 
       alert(username); //correct output 
      }); 
     </script> 
    </body> 
</html> 

,並在我的用戶/歡迎

router.get('/welcome', ensureAuthenticated, function(req, res){ 

    var test = req.query.wew; //data from ajax request 

    Item.find({username: test},function(err, docs, test){  
     //where username is the data 
     console.log(test); 
     res.render('welcome', {docs:docs}); 
    }); 
}); 

此代碼不能正常工作。請幫忙:/

+0

「的代碼是不工作」是非常廣泛 - 你能解釋一下你的問題嗎 –

+0

我想將ajax數據存儲到server.js中的一個變量中。第二組代碼是我的服務器 –

+0

,因此您需要將數據從瀏覽器發送到服務器? –

回答

0

你可以用socket.io。我用它在瀏覽器和node.js服務器之間進行雙向通信。

在客戶端,你會怎麼做:

function movePlayer() { 
    socket.emit ('doSomethingServerSide', {numVal: 4, usrName: 'KaiserSolze'}); 
} 

和服務器端,你會:

// A FUNCTION THAT LISTENS FOR A CALL FROM BROWSERS CONNECTED VIA SOCKET 
socket.on ('doSomethingServerSide', function (msg) { 
    // THEN YOU COULD REPORT TO ALL BROWSERS/CLIENTS THAT SOMETHING WAS DONE 
    io.sockets.emit ('reportToClients', msg); 
}); 

如果你決定走這條路有很多在這裏的職位,以幫助您從socket.io開始。

0

嘗試用HTTP給你的網站的完整URL和替換雙(//)與一個

$.ajax({ 
         type : 'GET', 
         url: 'http://<your application full url>/users/welcome', 
         data : { 
          wew: username 
         } 
        }); 

或者你可以試試下面

$.ajax({ 
      url: "https://stackoverflow.com/users/welcome?wew="+username, 
      type: "GET", 
      contentType: "application/json", 
      dataType: "json", 

}); 
相關問題