2017-09-19 7 views
-2

현재 자바 스크립트 클래스에 대한 과제를 진행하고 있으며 도움을 청하거나 시작 지시가 필요합니다. 이것은 사용자 입력을 통해 길이와 너비를 얻은 다음 영역과 둘레를 계산하고 텍스트 상자에 표시하는 매우 간단한 프로그램입니다.자바 스크립트 및 XHR 서버 요청

그 부분은 간단했지만, 사용자가 입력 한 길이와 너비를 node.js 표현 서버에 보내도록 프로그램을 변경해야합니다. 서버는 url에있는 사용자가 입력 한 2 개의 매개 변수를 사용하여 계산을 수행합니다. 계산이 완료된 후 영역 및 둘레 값이 json 객체에 반환됩니다.

이제 내가 겪고있는 두 가지 문제점은 익스프레스 서버에 사용자 입력을 보낼 수 없다는 점과 원래 .js 파일에서 반환 된 json 객체를 잡는 방법을 파악할 수 없다는 것입니다. 아래는 익스프레스 서버 파일 다음에 오는 주 JavaScript 파일입니다. 어떤 도움이나 조언을 주시면 감사하겠습니다.

  • 이 URL에 대한 요청을 수락 핸들러를 쓰기 "/ CALC /"
  • URL은 위의 두 URL의 PARAMS, 길이와 폭을 기대한다 :

    은 할당 지시했다. 예. 핸들러의 몸에서
  • http://localhost/calc/?length=1&width=1, 면적과 둘레를 계산하고 다음과 같이 JSON 객체를 반환 : { "영역": 1, "경계": 1}
  • 요청을 받아 다른 핸들러를 작성 이 처리기는 첨부 된 HTML 파일을 반환해야합니다. - HTML 및 JS 파일 (첨부)을 업데이트하여 클라이언트 측에서 계산하는 대신 새 응용 프로그램 서버를 활용하십시오.

    function calculate(){ 
    
    // alert statements are great for troublshooting, they let you know where you are in the program. 
    console.log('You just clicked the button!'); 
    alert("This must be a number, not something else"); 
    
    /* 
    Get a reference to the HTML element with the ID of 'length'. 
    Please note, this is a reference to the HTML element, NOT WHAT YOU TYPED IN THE BOX! 
    If you need to get what you typed in the box you will nedd to access the element's 'value' attribute, then convert it to a float. 
    */ 
    var length_element = document.getElementById('length'); 
    var length = parseFloat(length_element.value); 
    
    var width_element = document.getElementById('width'); 
    var width = parseFloat(width_element.value); 
    
    
    // Now make an XHR request to your server via the URL below. 
    // http://localhost:3000/calc?length=length&width=width 
    // Capture the results in the variables below 
    var xhttp = new XMLHttpRequest(); 
    xhttp.open("GET", "http://localhost:3000/calc/?legnth=" + length + "&width=" + width, true); 
    xhttp.send(null); 
    
    
    // Don't know what to do beyond this part or where to go from here. 
    var area = 
    var perimeter = 
    
    
    
    // If you need to set the 'value' attribute of a text box you can do it like this 
    var area_element = document.getElementById('area'); 
    area_element.value = area; 
    
    var perimeter_element = document.getElementById('perimeter'); 
    perimeter_element.value = perimeter; 
    
    } 
    

    두 번째 파일

    const express = require('express'); 
    const app = express(); 
    
    var path = require("path"); 
    
    app.get('/calc/', function (req, res) { 
        var length = req.query.length; 
        var width = req.query.width; 
        var area = length*width; 
        var perimeter = ((length*2) + (width*2)); 
        res.send({ "area": area, "perimeter": perimeter }); 
    }); 
    
    app.get('/', function(req,res){ 
        res.sendFile(path.join(__dirname+'/index.html')); 
        }) 
    
    app.listen(3000, function() { 
        console.log('Example app listening on port 3000!') 
    }); 
    
+0

'XMLHttpRequest'에 대한 좋은 참고 자료는 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest를 참조하십시오. – nilobarp

답변

0

당신은 기본적으로 xhttp.onloadxhttp의 오프 응답을 읽을 필요가있다. 간단한 예제가 있습니다

var xhttp = new XMLHttpRequest(); 
xhttp.open("GET", "http://localhost:3000/calc/?legnth=" + length + "&width=" + width, true); 
xhttp.send(); 

xhttp.onload = function (e) { 
    var response = xhttp.response; 
} 

서버 스크립트에서 보내는 내용에 따라 응답 데이터를 구문 분석해야 할 수 있습니다.

이보다 완벽한 솔루션을 돌봐 Content-Type 헤더 encoding 등 같은 다른 것들,하지만 당신은 당신이 순간을 위해 JSON.parse 멀리 할 수있는 기본적인 자바 스크립트에 충실 할 필요가 가정.