1. AJAX calcForm 연습하기 (ajax를 이용한 계산기)

2. AJAX 가격을 입력 후 구입 확인 버튼을 누르면 구입 가능한 물품 중 가장 비싼
   물품을 보내준다. 가격이 너무 적으면 구입 불가 라는 메세지를 보내준다.

3. 서버에서 현대(1400), 기아(1300), 쌍용(1500), 벤츠(3500), BMW(3200)
   빨강(100), 파랑(120), 초록(200), 노랑(130), 검정(80)
   차종, 색상의 합계를 응답으로 전송하여 화면에 가격을 출력하세요.

4. 함수 사용하기.
   3개의 수를 입력 받아 가장 큰 수 구하기.

 

1. app.js

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app).listen(81);

// 1. AJAX calcForm 연습하기
app.get('/Review1Ajax', function (req, res) {
  res.sendfile("calcForm.html");
});
app.get('/QuerySum', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1} + ${num2} = ${num1 + num2}`);
});
app.get('/QuerySubtraction', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1} - ${num2} = ${num1 - num2}`);
});
app.get('/QueryMultiply', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1} x ${num2} = ${num1 * num2}`);
});
app.get('/QueryDivision', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1} ÷ ${num2} = ${num1 / num2}`);
});
app.get('/QueryQuotient', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1}을 ${num2}로 나눈 몫은 : ${parseInt(num1 / num2)}`);
});
app.get('/QueryRemainder', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1}을 ${num2}로 나눈 나머지는 : ${num1 % num2}`);
});
app.get('/QuerySquare', function (req, res) {
  console.log(req.query);
  var num1 = Number(req.query.num1);
  var num2 = Number(req.query.num2);
  res.send(`${num1}^${num2} = ${Math.pow(num1,num2)}`);
});



// 2. AJAX 가격을 입력 후 구입 확인 버튼을 누르면 구입 가능한 물품 중 가장 비싼
// 물품을 보내준다. 가격이 너무 적으면 구입 불가 라는 메세지를 보내준다.
app.get('/Study1Ajax', function (req, res) {
  res.sendfile("Study1Ajax.html");
});
app.get('/QueryStore', function (req, res) {
  // var money = Number(req.query.money);
  // let priceArray = [1000,5000,10000,30000,50000,100000,500000];
  // var result;
  //
  // var priceLastIndex = priceArray.length - 1;
  // for (var i = priceLastIndex; i >= 0; i--) {
  //   console.log(i, money,  priceArray[i])
  //   if (money >= priceArray[i]) {
  //     result = "item" + String(i+1);
  //     break;
  //   } else {
  //     result = "구입 불가";
  //   }
  // }

  // 리스트 안에 딕셔너리!!!!
  var money = Number(req.query.money);
  var items = [
    {name: "item1", price: 1000},
    {name: "item2", price: 5000},
    {name: "item3", price: 10000},
    {name: "item4", price: 30000},
    {name: "item5", price: 50000},
    {name: "item6", price: 10000},
    {name: "item7", price: 50000},
  ];
  var result = "구입 불가";
  for (var i = 0; i < items.length; i++) {
    var eachItem = items[i];
    if (money > eachItem.price) {
      result = eachItem.name;
    } else {
      break;
    }
  }

  res.send(`${result}`);

});



// 3. 서버에서 현대(1400), 기아(1300), 쌍용(1500), 벤츠(3500), BMW(3200)
// 빨강(100), 파랑(120), 초록(200), 노랑(130), 검정(80)
// 차종, 색상의 합계를 응답으로 전송하여 화면에 가격을 출력하세요.
app.get('/carPrice', function (req, res) {
  res.sendfile("carPrice.html");
});
app.get('/calcCarPrice', function (req, res) {
  // 방법 1. select 박스의 value 값을 넘겨 받기
  // var num1 = Number(req.query.manufac);
  // var num2 = Number(req.query.color);

  // 방법 2. 프론트엔드에는 정보가 없고 백엔드에서 가격 DB를 소유한 상태에서 계산하기
  var manufac = req.query.manufac;
  var color = req.query.color;

  manufacDict = {"현대":1400,"기아":1300,"쌍용":1500,"벤츠":3500,"BMW":3200};
  colorDict = {"빨강":100,"파랑":120,"초록":200,"노랑":130,"검정":80};

  var manufacPrice = manufacDict[manufac];
  var colorPrice = colorDict[color];

  res.send(`${(manufacPrice + colorPrice)} 만원`);
});

console.log("server is running...")

 

2. calcForm.html (http://localhost:81/Review1Ajax)

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="text" placeholder="num1을 입력" id="num1">
    <input type="text" placeholder="num2를 입력" id="num2">
    <br><br>
    <input type="button" value="덧셈" id="sumBnt"></button>
    <input type="button" value="뺄셈" id="subtractionBnt"></button>
    <input type="button" value="곱셈" id="multiplyBnt"></button>
    <input type="button" value="나누기" id="divisionBnt"></button>
    <input type="button" value="몫" id="quotientBnt"></button>
    <input type="button" value="나머지" id="remainderBnt"></button>
    <input type="button" value="제곱" id="squareBnt"></button>

    <span id="result"></span>

  </body>
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
    $('#sumBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QuerySum',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#subtractionBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QuerySubtraction',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#multiplyBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QueryMultiply',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#divisionBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QueryDivision',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#quotientBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QueryQuotient',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#remainderBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QueryRemainder',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
    $('#squareBnt').click(function() {
      $.ajax({
        url : 'http://localhost:80/QuerySquare',
        data : {
          num1 : $('#num1').val(),
          num2 : $('#num2').val()
        },
        success : function(response) {
          $('#result').append("<br>" + response);
        }
      });
    });
  </script>


</html>

 

3. Study1Ajax.html (http://localhost:81/Study1Ajax)

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="text" placeholder="지갑에 얼마 있어요?" id="money">
    <input type="button" value="아이템" id="storeBnt">
    <br><br>
    <span id="result"></span>

  </body>
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
  // text 박스로 이동
  $("#money").focus();
  // 입력 상태로 만든다
  // $("#storeBtn").click(function(){
  //   getItemFormServer();
  // })
  // 13(엔터)키를 누른다
  // $("#money").keydown(function(key){
  //   if(key.keyCode == 13) {
  //     $("#getItemBtn").click();
  //   }
  // });


  $('#storeBnt').click(function() {
    $.ajax({
      url : 'http://localhost:80/QueryStore',
      data : {
        money : $('#money').val()
      },
      success : function(response) {
        $('#result').append("<br>" + response);
        // text 박스로 이동 -> 문자열 지우기
        $('#money').focus();
        $('#money').val("");
      }
    });
  });

  </script>
</html>

 

4. carPrice.html (http://localhost:81/carPrice)

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <select id="manufacturer" value="manufacturer"> <!-- 드롭박스 타입의 선택 상자 -->
      <option value="0">제조사</option>
      <option value="2100">현대</option>
      <option value="1300">기아</option>
      <option value="1500">쌍용</option>
      <option value="3500">벤츠</option>
      <option value="3200">BMW</option>
    </select>

    <select id="color" value="color"> <!-- 드롭박스 타입의 선택 상자 -->
      <option value="0">색상</option>
      <option value="100">빨강</option>
      <option value="120">파랑</option>
      <option value="200">초록</option>
      <option value="130">노랑</option>
      <option value="80">검정</option>
    </select>
    <input type="button" value="가격 확인하기" id="checkPrice">
    <br>
    <span id="result"></span>

  </body>

  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
    $("#checkPrice").click(function(){
      $.ajax({
        url : 'http://localhost:80/calcCarPrice',
        data : {
          // 방법 1.
          // manufac : $("#manufacturer option:selected").val(),
          // color : $("#color option:selected").val()

          // 방법 2.
          manufac : $("#manufacturer option:selected").text(),
          color : $("#color option:selected").text()

        },
        success : function(response) {
          // $('#result').append("<br>" + response);
          // $("#result").html(response);
          $("#result").html(`${response}`);
        }
      });
    });
  </script>

</html>

 

5. function.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="text" placeholder="num1을 입력" id="num1">
    <input type="text" placeholder="num2를 입력" id="num2">
    <input type="text" placeholder="num3를 입력" id="num3">

    <input type="button" value="가장 큰 수는?" id="Bnt"></button>
    <br><br>
    가장 큰 수는 : <span id="result"></span>

  </body>
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
    // 자바스크립트 함수 사용법
    function functionName1() {
      console.log(1);
    }

    var functionName2 = function() {
      console.log(2);
    }

    var result1 = functionName1();
    var result2 = functionName2();

    console.log("----------------------");
    // for문 예제
    var cnt = 0;
    for ( ; ; ) {
      cnt++;
      console.log(cnt);
      if(cnt>5) break;
    }
    console.log("----------------------");
    // 숫자 3개 입력 받아 가장 큰 수 구하기

    $('#Bnt').click(function () {
      var response = findLargeNumber();
      $('#result').html(response);
    })

    function findLargeNumber(num1, num2, num3) {
      var num1 = parseInt($('#num1').val());
      var num2 = parseInt($('#num2').val());
      var num3 = parseInt($('#num3').val());

      if (num1 == num2 == num3) {
        return num1
      } else if (num1 > num2) {
        if (num1 > num3) {
          return num1
        } else {
          return num3
        }
      } else {
        if (num2 > num3) {
          return num2
        } else {
          return num3
        }
      }
    }

  </script>
</html>

 

 

 

가장 큰 수 구하기 좀 더 좋은 버전

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app).listen(80);
console.log("server is running...")

// 1. 가장 큰 수 구하기 함수
app.get('/function', function (req, res) {
  res.sendfile("function.html");
});

var testVal = "abc";

app.get('/setVal', function (req, res) {
  testVal = req.query.val;
  res.send("ok");
});

app.get('/getVal', function(req, res) {
  res.send(testVal)
});
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <input type="text" name="num1">
    <input type="text" name="num2">
    <input type="text" name="num3">
    <input type="button" id="compareBtn" value="버튼">
    <br>
    가장 큰 수는 : <span id="result"></span>
  </body>
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script>
    $("#compareBtn").click(function(){
      var maxVal = getMax();
      console.log(maxVal);
      $("#result").html(maxVal);
    });

    function getMax(val1, val2, val3) {
      var val1 = $("input[name=num1]").val();
      var val2 = $("input[name=num2]").val();
      var val3 = $("input[name=num3]").val();
      var maxVal = val1;

      console.log(val1);
      console.log(val2);
      console.log(val3);

      // console.log(maxVal);

      if (maxVal < val2) {
        maxVal = val2;
        // console.log(maxVal);
      }

      if (maxVal < val3) {
        maxVal = val3;
        // console.log(maxVal);
      }

      return maxVal;
    }

  </script>
</html>

 

+ Recent posts