简体   繁体   中英

jquery ajax not receiving node.js response properly

Client side code:

  for(var i =0; i < 1; i++) {
    void function(item) {
        alert(item);
        $.ajax({
          url : "/documents/ajax/" + item,
          dataType : "text",
          success : function(data) {
            alert("data");
          },
          error: function (xhr, ajaxOptions, thrownError) {
            alert('Error: ' + error.message);
          }
        });
    }(featuredItems.eq(i).text().trim());
  }

Node.js code:

app.get('/documents/ajax/:id.:format?', function(req, res) {
  console.log("Request Received");
  res.send("Response");
  res.end();

});

With this code I am not able to receive the response on client side.

If I do a ctrl-c on my node server, then success alert is popped up.

Please help/

UPDATE:

If I comment out following lines then I receive response properly:

//  app.use(express.session({secret: 'secret_key'}));
//  app.use(passport.initialize());
//  app.use(passport.session());

You are using old style of $.ajax; read http://api.jquery.com/jQuery.ajax/

else no post/get method.

If you think you have problem with express, just create new clear app from terminal for testing : express -s myapp

here's my $.ajax code:

$('.form-2').on('submit', function(e) {
    e.preventDefault();
        var data = {};
            data.email = $('#email').val().toLowerCase();
            data.pass = $('#password').val();
        $.ajax({ url: '/login'
               , type: 'POST'
               , data: JSON.stringify(data)
               , contentType: 'application/json'
            })
            .done(function(data) {
                if (data.access == 'logged') ...
            });
});

server:

app.post('/login', function(req, res, next) {
    res.json({ access: 'logged' });
});

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