Symfony-如何使用JQuery / AJAX将简单数据存储到MySQL数据库中?

时间:2018-09-17 15:06:58

标签: php jquery ajax symfony

我正在尝试将div元素中的简单数据(文件标题)存储到Mysql db中。.有人可以指出我的代码中的错误吗? 这是我的秘诀:

$( document ).ready(function() {

    $( "#store-button" ).click(function() {
        var title = $( "#pdf-title" ).text();
        storeData(title);
    });

});


function storeData(title)
{
    $.ajax({
        type: "POST",
        url: '{{ path('store') }}',
        data: { title: title } ,

        success: function (data) {
            // this is executed when ajax call finished well
            alert('content of the executed page: ' + data);
        },
        error:function(error){
            alert('Error: data couldnt be created');
            console.log(error);
        }
    });
}

这是我的控制器:

/**
 * @Route("/store", name="store")
 * @Method({"GET", "POST"})
 */
public function storeAction(Request $request)
{
    $data = new Data();
    $data->setFileName($request->request->get("title"));
    $em = $this->getDoctrine()->getManager();
    $em->persist($data);
    $em->flush();

}

1 个答案:

答案 0 :(得分:0)

通常需要对通过jquery传递的

json数据进行字符串化,因此您可以尝试执行以下操作:

function storeData(title)
{
    var data = {title: title};
    $.ajax({
        type: "POST",
        url: '{{ path('store') }}',
        data: JSON.stringify(data),

        success: function (data) {
            // this is executed when ajax call finished well
            alert('content of the executed page: ' + data);
        },
        error:function(error){
            alert('Error: data couldnt be created');
            console.log(error);
        }
    });
}