자바스크립트에서 db로 변수를 어떤 방식으로 보낼 수 있는지 궁금합니다

자바스크립트에서 db로 변수를 어떤 방식으로 보낼 수 있는지 궁금합니다

작성일 2023.05.25댓글 1건
    게시물 수정 , 삭제는 로그인 필요

이번에 간단히 데이터베이스와 연동된 웹게임 페이지 만드는 연습을 하게되었는데 아래 자바스크립트 코드에서 score 변수를 mysql에 있는 db에 보내고 싶은데 인터넷에서 찾아보니 방법이 너무 다양해서 어떤 방식을 쓰는 것이 가장 베스트일지 궁금합니다. 아래는 코드입니다.
let canvas = document.querySelector('#canvas');
let ctx = canvas.getContext('2d'); // context 란 뜻으로 ctx

canvas.width = window.innerWidth - 100;
canvas.height = window.innerHeight - 100;
ctx.fillStyle = 'black';
ctx.fillRect(0,0, canvas.width, canvas.height)

let dinoImg = new Image();
dinoImg.src = 'dinosaur.png';
let dino = {
    x: 10,
    y: 200,
    width: 40,
    height: 50,
    draw() {
        // ctx.fillStyle = 'green';
        // ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.drawImage(dinoImg, this.x, this.y);
    }
}

class Cactus {
    constructor() {
        this.width = 20 + getRandomInt(-3, 6);
        this.height = 30 + getRandomInt(-3, 6);
        this.x = 500;
        this.y = 250 - this.height;
    }
    draw() {
        ctx.fillStyle = 'green';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
}

let timer = 0;
let cactusArr = [];
let gameState = 0; // 0: end, 1: start
let jumpState = 0; // 0: default, 1: jumping
let jumpTimer = 0;
let animation;
let life = 5;
let score = 0;

function frameAction() {
    animation = requestAnimationFrame(frameAction);
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    timer += 1;
    
    if(timer % 120 == 0){
        let cactus = new Cactus();
        cactusArr.push(cactus);
    }
//점수관련함수
    cactusArr.forEach((a, i, o)=>{
        if(a.x < 0){
            o.splice(i, 1);
            score += 10;
            document.querySelector('#score').innerHTML = score;
        } else if(collisionDetection(dino, a) < 0){
            o.splice(i, 1);
        }
        
        a.x -= 2;
        a.draw();
    })    

    if(jumpState == 1){
        jumpTimer++; 
        dino.y -= 2;
    }
    if(jumpTimer > 50){
        jumpState = 0;
        jumpTimer = 0;
    }
    if(jumpState == 0){
        if(dino.y < 200){
            dino.y += 2;
        }
    }

    drawLine();
    dino.draw();
}

document.addEventListener('keydown', (e)=>{
    if(e.code == 'Space'){
        if(gameState == 0){
            gameState = 1; // 게임실행
            frameAction();
            document.querySelector('h2').style.display = 'none';
        } else if(gameState == 1){ // 게임실행중일때 스페이스누르면
            jumpState = 1; // 점프중으로 변경
        }
    }
})

function collisionDetection(dino, cactus){
    let xValue = cactus.x - ( dino.x + dino.width );
    let yValue = cactus.y - ( dino.y + dino.height );
    if( xValue < 0 && yValue < 0 ){ // 충돌!
        // 충돌 시 실행되는 코드
        life--;
        document.querySelector('#life').innerHTML = life;
        if(life == 0){
            alert('게임 오버입니다');
            gameState = 0;
            cancelAnimationFrame(animation);
            // ctx.clearRect(0, 0, canvas.width, canvas.height); // 작동이 안되서 새로고침으로 대체
            location.reload();
        }
        return -1;
    } else {
        return 1;
    }
}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min)) + min; //최댓값은 제외, 최솟값은 포함
}

function drawLine(){
    ctx.beginPath();
    ctx.moveTo(0, 250);
    ctx.lineTo(600, 250);
    ctx.stroke();
}



profile_image 익명 작성일 -

자바스크립트에서 MySQL과 같은 데이터베이스에 접근하려면 일반적으로 서버 측 언어(예: PHP, Node.js)를 사용하여 데이터베이스와 통신해야 합니다. 클라이언트 측 자바스크립트에서는 직접 데이터베이스에 접근할 수 없습니다.

따라서, 서버 측에서 클라이언트 측으로 데이터를 보내는 방법 중 하나는 Ajax를 사용하는 것입니다. Ajax를 사용하면 클라이언트 측에서 서버 측으로 HTTP 요청을 보내고, 서버 측에서는 해당 요청을 처리하여 데이터를 반환할 수 있습니다.

아래는 간단한 Ajax 예제입니다.

```javascript

let score = 100; // 보낼 데이터

let xhr = new XMLHttpRequest();

xhr.open('POST', '/save-score.php'); // 서버 측 파일 경로

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.onload = function() {

if (xhr.status === 200) {

console.log(xhr.responseText); // 서버 측에서 반환한 데이터

}

};

xhr.send('score=' + score); // 데이터를 보냄

```

위 예제에서는 POST 방식으로 '/save-score.php' 파일에 score 데이터를 보내고 있습니다. 서버 측에서는 해당 파일에서 score 값을 받아서 MySQL과 같은 데이터베이스에 저장할 수 있습니다.

하지만, 이 예제는 단순히 Ajax의 개념을 설명하기 위한 것이며, 실제로는 보안 문제 등 여러 가지 이유로 이렇게 직접 데이터베이스에 접근하는 것은 권장되지 않습니다. 대신, 서버 측에서 데이터베이스와의 통신을 담당하는 API를 만들어서 사용하는 것이 좋습니다. 이를 위해서는 서버 측 언어(예: PHP, Node.js)를 사용하여 API를 만들어야 합니다.

정말 힘들게 짜내서 답변드렸어용^^

답변확정 부탁드려요^^ (감사감사합니다)

쇼핑몰 혹은 Application 개발 언어들의...

... 어떤 방식으로 웹 페이지를 코딩하든, 아파취와 mod_perl을 이용하면 최고로 만들어 낼 있습니다. ASP가... 자바스크립트와 거의 유사한 jscript, 펄, 심지어 Python을 써서...

사이버 침해사고의 사고 원인 분석...

... 즉 금융부정과 관련된 범죄 및 은행․비은행의 임직원에 의한 직무와 관련된 범죄로 정의할 있다. 여기서 금융부정이란 예금 또는 자금획득의 방식이 은행법 등의...

컴퓨터 관련(IT) 용어 20개 알려주세요

... 위해서, 어떤 단말이 데이터를 송출 중일 때 다른 복수의 단말이 동시에 데이터를 송출할 있도록 하는 제어방식을 말한다. ATM 송출정보는 48바이트의 정보와...

아이디 중복값 체크 질문!

... 어떤걸 공부해야 디비값이랑 체크할수있는지 궁금합니다 코드를 봐도 이해가 안되는 부분이 많아서요..... 값을 자바스크립트변수 var id가 가져오게 됩니다....

php,html 질문입니다.내공걸어요...

... 공란이 있는지 확인해주는 스크립트로 가게... 틀리다면 어떤방식으로 해야하는지 궁금합니다. 내공... 연산할 있는 방법은 없을겁니다.. 자바 스크립트라...