sourcetip

html 양식 데이터를 사용하여 JSON 개체를 보내는 방법

fileupload 2023. 2. 9. 22:28
반응형

html 양식 데이터를 사용하여 JSON 개체를 보내는 방법

HTML 폼은 다음과 같습니다.

<html>
<head><title>test</title></head>
<body>
    <form action="myurl" method="POST" name="myForm">
        <p><label for="first_name">First Name:</label>
        <input type="text" name="first_name" id="fname"></p>

        <p><label for="last_name">Last Name:</label>
        <input type="text" name="last_name" id="lname"></p>

        <input value="Submit" type="submit" onclick="submitform()">
    </form>
</body>
</html>

사용자가 [Submit]를 클릭했을 때 이 폼의 데이터를 JSON 오브젝트로 서버에 보내는 가장 쉬운 방법은 무엇입니까?

업데이트: 여기까지 왔는데 작동하지 않는 것 같습니다.

<script type="text/javascript">
    function submitform(){
        alert("Sending Json");
        var xhr = new XMLHttpRequest();
        xhr.open(form.method, form.action, true);
        xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
        var j = {
            "first_name":"binchen",
            "last_name":"heris",
        };
        xhr.send(JSON.stringify(j));

내가 뭘 잘못하고 있지?

완전한 폼 데이터를 어레이로 가져와 json 문자열화합니다.

var formData = JSON.stringify($("#myForm").serializeArray());

나중에 아약스에서 사용하실 수 있습니다.또는 Ajax를 사용하지 않는 경우 숨겨진 텍스트 영역에 넣고 서버로 전달합니다.이 데이터가 일반 형식 데이터를 통해 json 문자열로 전달되면 디코딩해야 합니다.그러면 모든 데이터가 배열로 표시됩니다.

$.ajax({
  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"
});

HTML은 폼 데이터에서 JSON을 생성하는 방법을 제공하지 않습니다.

클라이언트에서 처리하려면 JavaScript를 사용하여 다음을 수행해야 합니다.

  1. DOM을 통해 폼에서 데이터를 수집합니다.
  2. 그것을 사물 또는 배열로 정리하다
  3. JSON.stringify를 사용하여 JSON 생성
  4. XMLHttpRequest를 사용하여 게시합니다.

계속 하는 게 좋을 거야application/x-www-form-urlencodedJSON 대신 서버에서 데이터를 처리하고 있습니다.양식에 JSON 데이터 구조의 이점을 얻을 수 있는 복잡한 계층이 없습니다.


질문의 주요 개서에 대한 응답으로 업데이트...

  • JS에는 없습니다.readystatechange핸들러이므로 응답은 아무것도 하지 않습니다.
  • 기본 동작을 취소하지 않고 Submit 버튼을 클릭하면 JS가 트리거됩니다.브라우저는 JS 기능이 완료되는 즉시 (정규적인 방법으로) 양식을 제출합니다.

FormData API 사용

  1. FormData API를 사용하여 폼 데이터 캡처formData= new FormData(form)
  2. 다음을 사용하여 JSON으로 변환JSON.stringify(Object.fromEntries(formData))
  3. 이 계층화된 json을 Ajax 페이로드로 보내기
var form = document.getElementById('myForm');
form.onsubmit = function(event){
        var xhr = new XMLHttpRequest();
        var formData = new FormData(form);
        //open the request
        xhr.open('POST','http://localhost:7000/tests/v1.0/form')
        xhr.setRequestHeader("Content-Type", "application/json");

        //send the form data
        xhr.send(JSON.stringify(Object.fromEntries(formData)));

        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                form.reset(); //reset form after AJAX success or do something else
            }
        }
        //Fail the onsubmit to avoid page refresh.
        return false; 
    }

여기 기사에서 발췌:https://metamug.com/article/html5/ajax-form-submit.html

다음과 같은 작업을 수행할 수 있습니다.

<html>
<head>
    <title>test</title>
</head>

<body>
    <form id="formElem">
        <input type="text" name="firstname" value="Karam">
        <input type="text" name="lastname" value="Yousef">
        <input type="submit">
    </form>
    <div id="decoded"></div>
    <button id="encode">Encode</button>
    <div id="encoded"></div>
</body>
<script>
    encode.onclick = async (e) => {
        let response = await fetch('http://localhost:8482/encode', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
        })

        let text = await response.text(); // read response body as text
        data = JSON.parse(text);
        document.querySelector("#encoded").innerHTML = text;
      //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/> 
      //                                                  Last name = ${data.lastname} <br/>
      //                                                  Age    = ${data.age}`
    };

    formElem.onsubmit = async (e) => {
      e.preventDefault();
      var form = document.querySelector("#formElem");
     // var form = document.forms[0];

        data = {
          firstname : form.querySelector('input[name="firstname"]').value,
          lastname : form.querySelector('input[name="lastname"]').value,
          age : 5
        }

        let response = await fetch('http://localhost:8482/decode', {
                method: 'POST', // or 'PUT'
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data),
        })

        let text = await response.text(); // read response body as text
        document.querySelector("#decoded").innerHTML = text;
    };
</script>
</html>

코드는 정상이지만 실행되지 않았습니다. 제출 버튼의 원인 [type="comething"]을(를) 유형=버튼으로 대체하십시오.

<input value="Submit" type="button" onclick="submitform()">

폼이 선언되지 않았습니다.

let form = document.forms[0];
xhr.open(form.method, form.action, true);

늦었지만 물건이 필요한 분들을 위해 html만 사용해도 방법이 있습니다.PHP와 같은 일부 서버 측 프레임워크에서는 다음 코드를 작성할 수 있습니다.

<form action="myurl" method="POST" name="myForm">
        <p><label for="first_name">First Name:</label>
        <input type="text" name="name[first]" id="fname"></p>

        <p><label for="last_name">Last Name:</label>
        <input type="text" name="name[last]" id="lname"></p>

        <input value="Submit" type="submit">
    </form>

따라서 입력 이름을 다음과 같이 설정해야 합니다.object[property]물건을 받았기 때문에.위의 예에서는 다음 JSON을 사용하여 데이터를 얻었습니다.

{
"name": {
  "first": "some data",
  "last": "some data"
 }
}

2022년에 순수 자바스크립트를 사용하고 싶다면...

const ajax = async (config) => {
    const request = await fetch(config.url, {
        method: config.method,
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config.payload)
    });
    response = await request.json();
    console.log('response', response)
    return response
}

// usage
response = ajax({
    method: 'POST',
    url: 'example.com',
    payload: {"name": "Stackoverflow"}
})

마이크로 라이브러리 필드 어시스턴트는 정확히 다음과 같은 작업을 수행합니다.collectValues(formElement)는 입력 필드에서 정규화된 json을 반환합니다(즉, 체크박스를 boulan으로, 스트링으로 선택하는 등).

HTML 양식만으로 JSON 메시지를 전달할 수 있는 방법을 찾았습니다.

이 예는 GraphQL용이지만 JSON 메시지를 기다리는 모든 엔드포인트에서 작동합니다.

기본적으로 GraphqhQL에서는 쿼리 또는 변환을 JSON 형식으로 추가할 수 있는 Operations라는 파라미터가 필요합니다.이 경우 allUsers를 취득하여 각 사용자의 userId를 반환하도록 요구하는 쿼리를 실행합니다.

{ 
 allUsers 
  { 
  userId 
  }
}

텍스트 입력을 사용하여 사용 방법을 시연하고 있지만 숨겨진 입력으로 변경하여 사용자에게 쿼리를 숨길 수 있습니다.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

이 다이내믹을 작성하려면 JS가 양식을 제출하기 전에 텍스트 필드의 값을 쿼리 문자열로 전송해야 합니다.어쨌든 나는 이 접근법이 매우 흥미롭다는 것을 알았다.도움이 됐으면 좋겠다.

언급URL : https://stackoverflow.com/questions/22195065/how-to-send-a-json-object-using-html-form-data

반응형