首页 > 解决方案 > Symfony-如何使用 JQuery/AJAX 将简单数据存储到 MySQL 数据库中?

问题描述

我正在尝试将 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();

}

标签: phpjqueryajaxsymfony

解决方案


通过 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);
        }
    });
}

推荐阅读