Json响应显示

时间:2016-03-25 01:30:48

标签: jquery ajax symfony

我是symfony和ajax的新手,我想在每次跟随this教程时都提交表单而不刷新页面,页面上的所有内容都会提交到数据库,但问题是我在浏览器中收到此消息

{"message":"Success!"}

这就是我在我的控制器中所拥有的。

$bon = new Bons();
    $form = $this->createForm('AppBundle\Form\BonsType', $bon);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($bon);
        $em->flush();

        return new JsonResponse(array('message' => 'Success!'), 200);
    }

    return $this->render('bons/new.html.twig', array(
        'bon' => $bon,
        'form' => $form->createView(),
    ));

ajax部分:

$(document).ready(function() {
        $('body').on('submit', '.myForm', function (e) {

            e.preventDefault();

            $.ajax({
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                data: $(this).serialize()
            })
            .done(function (data) {
                if (typeof data.message !== 'undefined') {
                    alert(data.message);
                }
            })
            .fail(function (jqXHR, textStatus, errorThrown) {
                if (typeof jqXHR.responseJSON !== 'undefined') {
                    if (jqXHR.responseJSON.hasOwnProperty('form')) {
                        $('#form_body').html(jqXHR.responseJSON.form);
                    }

                    $('.form_error').html(jqXHR.responseJSON.message);

                } else {
                    alert(errorThrown);
                }

            });
        });
    });

有没有办法在不重定向或刷新页面的情况下提交表单

1 个答案:

答案 0 :(得分:1)

原来你的问题很简单。您只需要像这样添加dataType:

$.ajax({
    type: $(this).attr('method'),
    dataType: "json",
    url: $(this).attr('action'),
    data: $(this).serialize()
})

我想告诉你我通常做的事情

我的php文件如下所示:

$json = array();
$my_variable = $_POST('variable_name'); // or however I get the value
if(something == something)
    $json['success'] = 'It was successful';
else
    $json['error'] = 'Something went wrong';
die(json_encode($json));

我的JS看起来像这样:

$('.update_class').click(function(){
    var variable_I_am_sending = $(this).data('something');
    $.post('path_to_php', {variable_name: variable_I_am_sending}, function(data, result, xhr){
        if(result == 'success')
            if(data.success)
                alert(data.success);
            else
                alert(data.error);
        else
            alert('ajax call failed');
    }, "json");
});