[英]jQuery: Post data from ajax response
我正在通過 ajax 發布一個表單,該表單具有“bookroom_ajax”類,ajax 結果在一個單獨的 div 中與“ajax_response”類一起返回,這工作正常。
但是我想在提交它的同一個表單中返回結果,但是如果我將 ajax 響應類添加到表單中,它就不再起作用了:
<form class="bookroom_ajax ajax_response">
這是 jQuery ajax 代碼:
jQuery(document).ready(function($) {
$(document).on("click",'#bookingbutton2', function() {
$('.ajax_response').html('<img src="http://mailgun.github.io/validator-demo/loading.gif" alt="Loading...">');
$.ajax({
type: 'POST',
url: AJAX_URL,
data: $('.bookroom_ajax').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('.bookroom_ajax')[0].reset();
}
$('.ajax_response').html(response.content);
}
});
});
});
在我看來,您的 AJAX 響應不包含預期數據。 這是為什么。 單擊按鈕后,您將表單的內容更改為加載微調器。 由於bookroom_ajax
和ajax_response
都指向同一個元素,您的序列化數據可能不包含您期望它包含的內容(因為表單中不再有表單元素)。 結果,您的服務器不會以您期望的方式響應,並且不包含您嘗試使用.html()
放回表單元素中的數據。
$(document).on("click",'#bookingbutton2', function() {
// Form content replaced by a spinner
$('.ajax_response').html('<img src="http://mailgun.github.io/validator-demo/loading.gif" alt="Loading...">');
$.ajax({
type: 'POST',
url: AJAX_URL,
// Form doesn't contain data, so serialization doesn't result in expected data to be sent to the server
data: $('.bookroom_ajax').serialize(),
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('.bookroom_ajax')[0].reset();
}
// Response doesn't contain expected data
$('.ajax_response').html(response.content);
}
});
});
這是我基於對您的代碼片段的分析的假設。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.