NodeJS Ajax

Add JavaScript in jade

Write directly

script.
  // JavaScript

Read file

script(type='text/javascript', src='./jquery.min.js');

Example

index.jade

Jade file.
It includes client side javascript. It has also Ajax request codes.

extends layout
block content
  script.
    function func() {
      var form = new FormData(document.querySelector("#form1"));
      var xhr = new XMLHttpRequest();
      xhr.open('POST', '/', true);
      xhr.responseType = 'json';
      xhr.onload = function(e) {
        if (this.status = 200) {
          var result = this.response;
          var msg = ''
           + '' + result.mail + ''
           + ''
           + '
Tel:' + result.tel + '
'; document.querySelector('#msg').innerHTML = msg; } }; xhr.send(form); } h1= title p Welcome to #{title} p#msg #{msg} form#form1(method='post', action='javascript:return false;') table tr td p Name: td input#name(type='text', name='name') tr td td input(type='button' value='Ajax' onclick='func();')

index_post.js

Handle POST request of Ajax from index.jade

var data = {
  yoona:{mail:'yoona@snsd.com', tel:'090-1111-1111'},
  taeyeon:{mail:'taeyeon@snsd.com', tel:'090-2222-2222'}
};

exports.index = function(req, res){
  var name = req.body.name;
  var result = data[name];
  if (result == undefined) {
	  result = {mail:'Not found', tel:'Not found'};
  }
  res.send(result);
};

index.js

var data = {
  yoona:{mail:'yoona@snsd.com', tel:'090-1111-1111'},
  taeyeon:{mail:'taeyeon@snsd.com', tel:'090-2222-2222'}
};

exports.index = function(req, res){
  var name = req.body.name;
  var result = data[name];
  if (result == undefined) {
	  result = {mail:'Not found', tel:'Not found'};
  }
  res.send(result);
};

With jQuery