S
S
Stopy2015-04-20 22:15:17
JavaScript
Stopy, 2015-04-20 22:15:17

How to return a response to an AJAX request in nodejs?

Here in php everything is clear, we just give something to the request through 'echo'
How about in nodejs? res.end() ?
But code like this doesn't work
Client:

$.post('/get_comments', {id: parseInt($(this).parent().attr('data-id')), function(data){
        console.log(data);
 }});

Server:
var ShowComments_Model = require('../models/ShowComments_Model.js');

module.exports = function (req, res, db, next) {
    res.json({data: 12});
}


Code accepting requests:
var ShowComments_Controller = require('./controllers/ShowComments_Controller.js');
app.post('/get_comments', function(req,res,next) {
  ShowComments_Controller(req, res, db, next);
});

Also on the server, I tried to give both the string and the rendered part of the template res.render('some', {data: data});
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Timofey, 2015-04-20
@Stopy

First, jQuery has a data function and you can (and even should) shorten the code to $(this).parent().data('id').
Second, the url /get_comments?jsoncallback=? obviously something is wrong, namely the second question mark.
Thirdly, according to the res.end() documentation for Express:
Although there is an optional data parameter, it's better to write res.json({data: 12}); if only because such a record is shorter and more fun.
Based on what is in the question, it’s impossible to say about other errors, so if it doesn’t help, then show the express call code (it’s trite, but suddenly, for example, you call express.get, although the request is post?)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question