[javascript] JSON을 서버에 보내고 JQuery없이 JSON을 반환합니다.

JSON (문자열화할 수 있음)을 서버에 보내고 JQuery를 사용하지 않고 사용자 측에서 결과 JSON을 검색해야합니다.

GET을 사용해야하는 경우 JSON을 매개 변수로 어떻게 전달합니까? 너무 길어질 위험이 있습니까?

POST를 사용해야하는 경우 onloadGET에서 해당 기능을 어떻게 설정 합니까?

아니면 다른 방법을 사용해야합니까?

이 질문은 간단한 AJAX를 보내는 것이 아닙니다. 중복으로 닫아서는 안됩니다.



답변

POST 방식을 사용하여 JSON 형식으로 데이터 송수신

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
xhr.send(data);

GET 메소드를 사용하여 JSON 형식으로 데이터 송수신

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "hey@mail.com", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

PHP를 사용하여 서버 측에서 JSON 형식의 데이터 처리

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

HTTP Get 요청 길이 제한은 사용되는 서버와 클라이언트 (브라우저) 모두에 따라 2kB-8kB입니다. URI가 서버가 처리 할 수있는 것보다 긴 경우 서버는 414 (Request-URI Too Long) 상태를 반환해야합니다.

참고 누군가 내가 상태 값 대신 상태 이름을 사용할 수 있다고 말했습니다. 즉, xhr.readyState === xhr.DONE대신 사용할 수 있습니다 xhr.readyState === 4. 문제는 Internet Explorer가 다른 상태 이름을 사용하므로 상태 값을 사용하는 것이 좋습니다.


답변

새 API 가져 오기 사용 :

const dataToSend = JSON.stringify({"email": "hey@mail.com", "password": "101010"});
let dataReceived=""; 
fetch("",{credentials:'same-origin',mode:'same-origin',method:"post",body:dataToSend})
              .then(resp => {
                if(resp.status==200){
                   return resp.json()
                }else{
                    console.log("Status: "+resp.status);
                    return Promise.reject("server")
                }
              })
           .then(dataJson =>{
                 dataReceived = JSON.parse(dataJson);
             })
              .catch(err =>{
                if(err=="server")return
                console.log(err);
            })
            
 console.log(`Received: ${dataReceived}`)                

서버가 200 (ok)이 아닌 다른 상태를 보낼 때 처리해야합니다. 공백으로두면 json을 구문 분석하려고 시도하지만없는 경우 오류가 발생하므로 해당 결과를 거부해야합니다.


답변