반응형
JSON 형식의 POST 데이터
JSON 형식으로 변환 한 다음 JavaScript 함수로 게시하는 데 필요한 데이터가 있습니다.
<body onload="javascript:document.myform.submit()">
<form action="https://www.test.net/Services/RegistrationService.svc/InviteNewContact" method="post" name="myform">
<input name="firstName" value="harry" />
<input name="lastName" value="tester" />
<input name="toEmail" value="testtest@test.com" />
</form>
</body>
이것이 포스트가 지금 보이는 방식입니다. JSON 형식으로 값을 제출하고 JavaScript로 POST를 수행해야합니다.
jQuery를 원하는지 확실하지 않습니다.
var form;
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
다음은 jQuery 를 사용한 예입니다 .
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
var frm = $(document.myform);
var dat = JSON.stringify(frm.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
jQuery serializeArray 함수는 양식 값으로 Javascript 객체를 생성합니다. 그런 다음 필요한 경우 JSON.stringify 를 사용 하여 문자열로 변환 할 수 있습니다 . 그리고 당신은 또한 당신의 신체 온로드를 제거 할 수 있습니다.
다른 예는 여기에서 사용할 수 있습니다.
JSON을 서버에 보내고 JQuery없이 JSON을 반환합니다.
jans 응답과 동일하지만 XMLHttpRequest에 onreadystatechange 콜백을 설정하여 서버 응답을 확인합니다.
Using the new FormData object (and some other ES6 stuff), you can do this to turn your entire form into json:
let data = {};
let formdata = new FormData(theform);
for (let tuple of formdata.entries()) data[tuple[0]] = tuple[1];
and then just xhr.send(JSON.stringify(data));
like in Jan's original answer.
참고URL : https://stackoverflow.com/questions/1255948/post-data-in-json-format
반응형
'programing tip' 카테고리의 다른 글
Android 5.0 (Lollipop)에서 프로그래밍 방식으로 수신 전화에 응답하려면 어떻게해야하나요? (0) | 2020.09.21 |
---|---|
Is there something like instanceOf(Class c) in Java? (0) | 2020.09.21 |
데이터 테이블에 null 값이 있는지 확인하는 가장 좋은 방법 (0) | 2020.09.21 |
Vim에서 Python 코드 실행 (0) | 2020.09.21 |
Docker 오류 : 클라이언트와 서버의 버전이 동일하지 않습니다. (0) | 2020.09.21 |