강의

멘토링

로드맵

Hình ảnh hồ sơ của sowhat05168000
sowhat05168000

câu hỏi đã được viết

Hiểu JavaScript phụ trợ thông qua phát triển web Node.js

Triển khai tích hợp MySQL

c오류 같은데,, 실행이 안돼요

Viết

·

328

0

코드를 동일하게 작성한 것 같은데 자꾸 오류가 나네요.. response에도 뜨지 않고 ajaxsend 버튼을 눌러도 밑에 result가 뜨지 않아요

 

그래서 form.html에서 xhr 정보를 console.log로 찍어봤는데요

다 비어있어요... 어쩌면 좋을까요?

network에는 pending인 상태로 뜨네요

 

전체 코드는 아래에 첨부합니다

 

<form.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>email form</title>
  </head>
  <body>
    <form action="/email_post" method="post">
      email : <input type="text" name="email"><br/>
      <input type="submit">
    </form>

    <button class="ajaxsend">ajaxsend</button>

    <div class="result"></div>

    <script>
      document.querySelector('.ajaxsend').addEventListener('click', function () {
        var inputdata = document.forms[0].elements[0].value;
        sendAjax('http://localhost:3000/ajax_send_email', inputdata);
      })

      function sendAjax(url, data){
        var data = {'email' : data};
        data = JSON.stringify(data); // 문자열로 반환
        console.log(data);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', "application/json");
        xhr.send(data);
       
        console.log(xhr.response);
        console.log(xhr.responseText);
        console.log(xhr.responseType);
        console.log(xhr.responseURL);
        console.log(xhr.responseXML);
        console.log('readystate : ' + xhr.readyState);
        console.log('status : ' + xhr.status);
        console.log('statusText : ' + xhr.statusText);

       
        xhr.addEventListener('load', function() {
          console.log(xhr.responseText);
          var result=JSON.parse(xhr.responseText); // 문자열이니까 JSON.parse
          var resultDiv = document.querySelector(".result");

          if(result.result !=="ok") resultDiv.innerHTML="your email is not found";
          else resultDiv.innerHTML=result.name;
        })
      }
    </script>
  </body>
</html>

 

<app.js>

app.post('/ajax_send_email', function(req, res) {
  var email = req.body.email;
  var responseData = {};

  var query = connection.query(
    'select name from user where email="'+ email + '"',
    function (err, rows) {
    if(err) throw err;
    if(rows[0]){ // 첫번째 data 있으면
      responseData.result = "ok";
      responseData.name = rows[0].name;
    }
    else{    
      responseData.result = "none";
      responseData.name = "";
    }
    res.json(responseData)
  })
})

 

nodejsjavascriptexpress

Câu trả lời 1

0

sowhat0516님의 프로필 이미지
sowhat0516
Người đặt câu hỏi

참고로 jsman에 데이터는 있는 상황입니다. . payload도 출력돼요

Hình ảnh hồ sơ của sowhat05168000
sowhat05168000

câu hỏi đã được viết

Đặt câu hỏi