• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Node.js, Express 게시판 node.js강의 다 듣고 응용해서 하려는데 $.get 사용이 안돼요

node.js강의 다 듣고 응용해서 하려는데 $.get 사용이 안돼요

3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 글쓴이
  • #97128

    정재희
    참가자
    node.js강의 다 듣고 완성한거랑 javascript기본 답인데봐도 쓸모없음 파일(대회)과 섞어보려했는데요. 
    
    $.get("store.json").then((data) => { 이게 도무지 안됩니다.
    그 외에 로그인하고 글작성, 수정,삭제 ,마이페이등 등은 다 되는데요 요 store.json파일을 불러오는게 도무지 안됩니다.
    
    아래 내용은 index.ejs 파일을 가져왔습니다.
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
          crossorigin="anonymous"
        />
        <link href="/public/main.css" rel="stylesheet" />
        <title>Document</title>
      </head>
      <body>
        <%- include('nav.html') %>
        <div class="container">
          <input id="search" placeholder="검색어입력" />
        </div>
        <div class="container">
          <div class="search_box active"></div>
        </div>
        <div class="container">
          <div class="row product-list">
            <!-- <div class="col-md-3">
            < img src="">
            <h4>상품명 : </h4>
            <p>가격 : </p>
          </div> -->
          </div>
        </div>
        <div class="container basket-wrap" style="background: #e2e2e2">
          <h4>장바구니 (드래그 가능)</h4>
          <div class="row basket"></div>
        </div>
        <div class="container my-3">
          <h4>최종가격</h4>
          <p class="final-price"></p>
          <button class="buy">구매하기</button>
        </div>
        <div class="modal1" style="display: none">
          <div class="white-bg">
            <h4>성함</h4>
            <input type="text" id="name" />
            <h4>연락처</h4>
            <input type="text" id="phone" />
            <button class="show-receipt">입력완료</button>
            <div>
              <button class="close">닫기</button>
            </div>
          </div>
        </div>
        <div class="modal2" style="display: none">
          <div class="white-bg">
            <h4>영수증</h4>
            <canvas id="canvas" width="350" height="350"></canvas>
            <div>
              <button class="close">닫기</button>
            </div>
          </div>
        </div>
        <script
          src="https://code.jquery.com/jquery-3.6.0.min.js"
          integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
          crossorigin="anonymous"
        ></script>
        <script>
          let products = [];
          let cart = [];
          //====================
          //상품진열기능
          //====================
          $.get("store.json").then((data) => {
            products = data.products;
            products.forEach((a) => {
              $(".product-list").append(`
            <div class="col-md-3">
              <div class="item" draggable="true" data-id="${a.id}">
                < img src="${a.photo}">
                <h4>${a.title}</h4>
                <h4>${a.brand}</h4>
                <p>가격 : ${a.price}</p>
                <button class="add" data-id="${a.id}">담기</button>
              </div>
            </div>`);
            });
            //====================
            //장바구니 담는기능
            //====================
            function add(id) {
              let i = cart.findIndex((cart) => {
                return cart.id == id;
              });
              if (i == -1) {
                let product = products.find((a) => {
                  return a.id == id;
                });
                console.log(product);
                product.count = 1;
                cart.push(product);
              } else {
                cart[i].count++;
              }
              $(".basket").html("");
              cart.forEach((a) => {
                $(".basket").append(`
              <div class="col-md-3 bg-white">
                < img src="${a.photo}">
                <h4>${a.title}</h4>
                <h4>${a.brand}</h4>
                <p>${a.price}</p>
                <input type="number" value="${a.count}" class="item-count w-100">
            </div>`);
              });
              cal();
            }
            function cal() {
              let finalPrice = 0;
              cart.forEach((a) => {
                finalPrice += a.price * a.count;
              });
              $(".final-price").text(finalPrice + "원");
            }
            $(".add").on("click", function (e) {
              let id = e.target.dataset.id;
              add(id);
            });
            //.add 버튼 클릭하면 끝
            //====================
            //드래그로 장바구니 추가기능
            //====================
            $(".item").on("dragstart", function (e) {
              e.originalEvent.dataTransfer.setData("id", e.target.dataset.id);
            });
            $(".basket").on("dragover", function (e) {
              e.preventDefault();
            });
            $(".basket").on("drop", function (e) {
              let productId = e.originalEvent.dataTransfer.getData("id");
              console.log(productId, `productId`);
              //신기한건 console.log 삭제하면 안됨
              add(productId);
            });
            //===========================
            //검색기능 + 담기기능 추가
            //===========================
            $("#search").on("input", function () {
              let searchWord = $("#search").val();
              let searchProducts = products.filter((a) => {
                return a.title.includes(searchWord) || a.brand.includes(searchWord);
              });
              $(".search_box").html("");
              if (searchWord == "") {
                $(this).removeClass("active");
              } else {
                $(this).addClass("active");
                searchProducts.forEach((a) => {
                  $(".search_box").append(`
              <div class="col-md-2">
                <div class="item" draggable="true" data-id="${a.id}">
                  < img src="${a.photo}">
                  <h4>${a.title}</h4>
                  <h4>${a.brand}</h4>
                  <p>가격 : ${a.price}</p>
                  <button class="add" data-id="${a.id}">담기</button>
                </div>
              </div>`);
                });
                $(".item h4").each(function (i, html) {
                  let title = html.innerHTML;
                  title = title.replace(
                    searchWord,
                    `<span style="background:yellow">${searchWord}</span>`
                  );
                  console.log(title);
                  html.innerHTML = title;
                });
                $(".add").on("click", function (e) {
                  let id = e.target.dataset.id;
                  add(id);
                });
              }
            });
          });
          //====================
          //구매하기 기능 + 영수증 모달창
          //====================
          $(".buy").on("click", function () {
            $(".modal1").show();
            $(".show-receipt").on("click", function () {
              $(".modal1").hide();
              $(".modal2").show();
              let name = $("#name").val();
              let phone = $("#phone").val();
              let finalPrice = $(".final-price").text();
              let canvas = document.getElementById("canvas");
              let ctx = canvas.getContext("2d");
              ctx.font = "20px Arial";
              ctx.fillText(`이름 : ${name}`, 10, 50);
              ctx.fillText(`연락처 : ${phone}`, 10, 100);
              ctx.fillText(`최종가격 : ${finalPrice}`, 10, 150);
            });
          });
          $(".close").on("click", function () {
            $(".modal1").hide();
            $(".modal2").hide();
          });
          //$.get 끝
        </script>
      </body>
    </html>
     
    #97131

    codingapple
    키 마스터
    .json파일을 public 폴더에 넣어보거나 
    서버에서 json데이터 보내주는 기능을 하나 만들어줍시다
    #97203

    정재희
    참가자
    public안에 두고 경로 바꾸니 해결되었습니다 감사합니다 !!
3 글 보임 - 1 에서 3 까지 (총 3 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠