이름이 적힌 양식을 가지고 있습니다.orderproductForm
입력 수가 정의되지 않았습니다.
저는 jQuery.get이나 ajax 같은 것을 하고 싶습니다.Ajax를 통해 페이지를 호출하여 폼의 모든 입력을 전송합니다.orderproductForm
.
한 가지 방법은 다음과 같은 일을 하는 것입니다.
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
그러나 나는 모든 양식 입력을 정확히 알지 못한다.모든 양식 입력을 전송하는 기능이나 기능이 있습니까?
질문에 대한 답변
이것은 간단한 참고 자료입니다.
// this is the id of the form $("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
Ajax Form Plugin 또는 jQuery serialize 함수에서 ajaxForm/ajaxSubmit 함수를 사용할 수 있습니다.
Ajax Form:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
또는
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
송신 버튼을 누르면, ajaxForm이 송신합니다.axSubmit은 즉시 송신합니다.
시리얼라이즈:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX의 시리얼라이제이션 메뉴얼은, 이쪽입니다.
폼 요소에 정의되어 있는 Atribut을 사용하는 다른 유사한 솔루션:
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). --> </form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
}); </script>
몇 가지 유의해야 할 사항이 있습니다.
1. 폼을 제출하는 방법에는 여러 가지가 있습니다.
- 송신 버튼 사용
- Enter 키를 눌러서
- JavaScript에서 송신 이벤트를 트리거하여
- 디바이스나 장래의 디바이스에 따라서는, 보다 많은 것을 생각할 수 있습니다.
따라서 버튼 클릭 이벤트가 아닌 폼 제출 이벤트에 바인딩해야 합니다.이를 통해 현재와 미래의 모든 장치 및 보조 기술에서 당사의 코드가 확실하게 작동하게 됩니다.
2) 히작스
사용자가 JavaScript를 사용하도록 설정하지 않았을 수 있습니다.여기에서는 히작스 패턴이 좋습니다.여기서는 JavaScript를 사용하여 폼을 부드럽게 제어하지만 JavaScript가 실패하면 제출 가능한 상태로 둡니다.
HTML이 변경되어도 JavaScript를 업데이트할 필요가 없도록 폼에서 URL과 메서드를 가져와야 합니다.
3. 방해받지 않는 자바스크립트
return false 대신 event.provent Default()를 사용하면 이벤트가 버블화될 수 있기 때문에 좋은 방법입니다.이를 통해 사용자 상호 작용을 모니터링하는 분석 스크립트 등 다른 스크립트를 이벤트에 연결할 수 있습니다.
속도
스크립트를 인라인으로 삽입하는 것이 아니라 외부 스크립트를 사용하는 것이 이상적입니다.스크립트 태그를 사용하여 페이지 머리 부분에 링크하거나 페이지 하단에 링크하여 속도를 높일 수 있습니다.이 스크립트는 사용자 경험을 방해해서는 안 되며 조용히 개선해야 합니다.
코드
상기의 모든 것에 동의하고, 송신 이벤트를 수신해, AJAX(히잡 패턴)를 개입시켜 처리한다고 가정하면, 다음과 같이 할 수 있습니다.
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
}); });
다음과 같은 방법으로 JavaScript를 통해 언제든지 폼 제출을 수동으로 트리거할 수 있습니다.
$(function() {
$('form.my_form').trigger('submit'); });
편집:
얼마 전에 이렇게 해서 플러그인을 쓰게 되었습니다.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
} })(jQuery)
폼 태그에 data-autosubmit 속성을 추가하면 다음과 같이 할 수 있습니다.
HTML
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here --> </form>
JS
$(function() {
$('form[data-autosubmit]').autosubmit(); });
FormData를 사용할 수도 있습니다(단, IE에서는 사용할 수 없습니다).
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
이것이 FormData를 사용하는 방법입니다.