简体   繁体   English

jQuery:从 ajax 响应发布数据

[英]jQuery: Post data from ajax response

I'm posting a form via ajax which has the class "bookroom_ajax", the ajax result is returned in a separately div with the class "ajax_response", this is working fine.我正在通过 ajax 发布一个表单,该表单具有“bookroom_ajax”类,ajax 结果在一个单独的 div 中与“ajax_response”类一起返回,这工作正常。

But I want to return the results inside the same form it is submited from, but if I add the ajax response class to the form it doesn't work any more:但是我想在提交它的同一个表单中返回结果,但是如果我将 ajax 响应类添加到表单中,它就不再起作用了:

<form class="bookroom_ajax ajax_response">

Here's the jQuery ajax code:这是 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);


        }
    });

});

});

It looks to me like your AJAX response doesn't contain expected data.在我看来,您的 AJAX 响应不包含预期数据。 Here's why.这是为什么。 As soon as the button is clicked, you change the content of the form to be a loading spinner.单击按钮后,您将表单的内容更改为加载微调器。 Since bookroom_ajax and ajax_response both point to the same element, your serialized data probably doesn't contain what you expect it to contain (because there are no form elements inside the form any more).由于bookroom_ajaxajax_response都指向同一个元素,您的序列化数据可能不包含您期望它包含的内容(因为表单中不再有表单元素)。 As a result, your server doesn't respond the way you expect it to and doesn't contain the data you are trying to put back inside the form element with .html() .结果,您的服务器不会以您期望的方式响应,并且不包含您尝试使用.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);


        }
    });

});

That is my hypothesis based on the analysis of your code snippet.这是我基于对您的代码片段的分析的假设。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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