jquery ajax json과 함께 양식 데이터 전송
저는 PHP/jquery를 처음 접했습니다 json 형식으로 axis(이름, 나이 등)와 같은 폼 필드에서 json 데이터를 보내는 방법을 묻고 싶습니다.안타깝게도 이에 대한 관련 정보를 찾을 수 없습니다. 동적으로 수행하는 것도 가능한가요?구글 검색은 수동으로 데이터를 쌓는 것과 같은 답만 돌려줍니다.예:name: X Y,age: 32, 등등.
그럴 방법이 있습니까?
도와주셔서 감사합니다!
편집:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
여기 간단한 것이 있습니다.
제 시험은 여기 있습니다. php는 시험용입니다.
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
이것이 제 색인입니다.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
두 파일이 동일한 디렉토리에 있습니다.
여기서 수락된 답변은 양식에서 json을 만들지만 json 내용은 URL로 인코딩된 내용의 문자열입니다.
보다 현실적인 json POST를 만들기 위해서는 serialize form data에서 JSON으로 솔루션을 제공하여formToJson함수와 덧셈contentType: 'application/json;charset=UTF-8'jQuery ajax 호출 매개 변수에 적용합니다.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
사용가능serialize()다음과 같이:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
JQuery를 사용하는 이유는 무엇입니까?
자바스크립트는 FormData api와 fetch를 제공하여 이를 쉽게 수행할 수 있습니다.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
참조 : https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
폼필드의 데이터를 서버(php)로 다시 전송하는 것은 일반적으로 PHP 내부의 superglobal array $_POST에서 찾을 수 있는 POST 방법에 의해 수행됩니다.서버로 보내기 전에 JSON으로 변환할 필요는 없습니다.간단한 예:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe@gmail.com" />
<button type="submit">Send!</button>
AJAX를 사용하면 페이지 새로 고침 없이도 동일한 작업을 수행할 수 있습니다.
언급URL : https://stackoverflow.com/questions/30680562/send-form-data-with-jquery-ajax-json
'programing' 카테고리의 다른 글
| PHP 준비문 SQL with where 값 (0) | 2023.10.27 |
|---|---|
| MySQL에서 grave accent(일명 백틱) 인용 문자의 의미는 무엇입니까? (0) | 2023.10.27 |
| brew - mysql은 설치 계정에 서명하지 않으면 사용할 수 없습니다. (0) | 2023.10.27 |
| Stripe Webhook에서 Parse.com 사용자 업데이트 (0) | 2023.10.27 |
| SQL Server 데이터베이스에 'Object'를 저장할 수 있습니까? (0) | 2023.10.27 |