2017-10-25 1 views
0

내 함수는 백엔드 서버의 데이터를 통해 구문 분석하고이 데이터를 사용하여 구문 분석 된 데이터를 HTML 문자열로 표시하는 renderHTML() 함수를 만듭니다. 데이터를 표시하고 체크 박스를 완벽하게 첨부 할 수도 있습니다. 나는 사용자가 체크 박스를 클릭 할 때 Ajax를 사용하여 questionid에서 수행 할 수있는 질문을 선택한 값을 보낼 수 있도록 questionid 값을 얻으려고합니다. questionid의 가치를 얻고 저장하고 Ajax를 통해 보내는 방법에 대해서는 잘 모르겠습니다.for 루프에서 확인란의 값을 얻는 방법

function receive() { 
    var text = document.getElementById("text").value; 

    var data = { 
    'text': text 
    }; 

    var xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function() { 
    if (xhr.readyState === 4) { 

     var ourData = xhr.responseText; 
     var parsedData = JSON.parse(ourData); 
     console.log(parsedData); 
     renderHTML(parsedData); 
    } 
    }; 
    xhr.open("POST", "URL", true); 
    xhr.send(JSON.stringify(data)); 
} 

var questionid; 

function renderHTML(data) { 
    var htmlString = ""; 

    for (i = 0; i < data.length; i++) { 
    htmlString += "<p><input type='checkbox' value='data[i].questionid'>" + 
     data[i].questionid + "." + "\n"; 
    htmlString += '</p>'; 
    } 

    response.insertAdjacentHTML('beforeend', htmlString); 

    var t = this; 
    var checkboxes = document.querySelectorAll('input[type="checkbox"]'); 

    for (var i = 0; i < checkboxes.length; i++) { 
    checkboxes[i].onclick = function() { 
     if (this.checked) { 
     console.log(this.questionid.value); 
     } 
     var xhr = new XMLHttpRequest(); 
     xhr.onreadystatechange = function() { 
     if (xhr.readyState === 4) { 

      var Data = xhr.responseText; 
      console.log(Data); 
      var parseData = JSON.parse(Data); 
     }; 
     xhr.send(JSON.stringify(data)); 

     } 
    } 
    } 
+0

:

이 코드는 당신이 찾고있는 것을한다. 당신은 어떤 지정도없이 그것을 선언하고 그것을 'data [i] .questionid'속성으로 사용하면, 이것을 조금 설명 할 수 있습니까? – Hanif

+0

'questionid'는'receive()'함수에서'parsedData'로부터받은 (name : value) 쌍의 이름입니다. 나는'questionid'의 값에 접근하여 onclick을 통해 백엔드 서버로 보낼 수있게하려고했습니다. – newbie

+0

"console.log (this.questionid.value);와 같은 값에 접근 할 수 없다고 생각합니다." "console.log (this.value);"시도해 주시겠습니까? " 입력 체크 박스에는 그런 속성이 없습니다. – Hanif

답변

0

찾고있는 것을 달성 할 수있는 방법은 여러 가지가 있습니다. 이를 위해, 당신은 두 가지 개념 중 하나를 이해하는 것이 필요합니다

  • 바인드
  • 폐쇄

그들 중 누구도 초보자를위한 쉽게 이해할 수 없지만 당신이 크게 당신이 한 번 코딩 기술을 개선하는 데 도움이됩니다 그들을 잡아라. 당신은 그들에 대해 각각 herehere을 읽을 수 있습니다.

코드의 문제점 (다른 세부 정보 중)은 i 값이 전역이므로 DOM이 렌더링되고 사용자가 확인란 중 하나를 클릭 할 때 모든 확인란이 동일한 값을가집니다. 나는 (마지막 하나).

bind은 항상 동일하게 유지 될 함수에 인수를 설정하여이를 해결하는 데 도움이됩니다.

클로저 해당 변수에 대한 참조를 저장하는 함수에서만 액세스 할 수있는 범위에 선언 된 변수 값을 저장하여이 문제를 해결하는 데 도움이됩니다.

여기 내가 가장 권장하는 가장 최신 구문을 사용하여 원하는 코드를 작성한 코드가 있습니다.

특히, fetch api에 대해 읽어 보시기 바랍니다. 이것은 http 요청을하는 훨씬 더 깔끔한 방법입니다. 'questionid'를하고 여기에 내가 확실하지 않다 무엇

function receive() { 
    const text = document.getElementById('text').value; 

    const options = { 
    method: 'POST', 
    body: JSON.stringify({ text }) 
    } 
    fetch("<the url here>", options) 
    .then(response => response.json()) 
    .then(data => { 
     renderHTML(JSON.parse(data)); 
    }) 
} 

function renderHTML(data){ 
    for (const x of data) { 
    const content = x.questionid; 
      // i'm asuming that the response html element already exists 
    response.insertAdjacentHTML('beforeend', `<p><input value="${content}" type="checkbox">${content}</p>`); 
    } 
    document.querySelectorAll('input[type="checkbox"]').forEach(input => { 
    input.addEventListener((e) => { 
     const options = { 
     method: 'POST', 
     body: JSON.stringify(e.target.value) 
     }; 
     fetch('<the second url here>', options).then(response => response.json()) 
     .then(data => { 

      // 'data' is the response you were looking for. 

     }) 
    }) 
    }) 
} 
+0

누락되었습니다. 모든 세미콜론. OP가 그들을 사용한다면 * 적어도 * 그들을 사용하십시오. – Tomalak

관련 문제