繁体   English   中英

jQuery:从 ajax 响应发布数据

[英]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_ajaxajax_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM