php - 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();
}
解决方案
通过 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);
}
});
}
推荐阅读
- javascript - 在 .NET 中使用 WebBrowser,可以使用突变观察器来监视 DIV 更改吗?
- javascript - 在提交表单时停止非 Ajax 文件上传
- flutter - 我的 Flutter 项目没有运行(错误消息)
- java - 嵌套类的理解
- python - discord.py 命令连接到机器人
- macos - 如何在 MacOS 上键入 ascii 代码 127?
- python - python子进程调用变量
- android - Android:使用 setDefaultNightMode()(特定于设备)更改主题时,以前的活动会闪烁白色
- python - 如何将字符串日期转换为熊猫日期和时间
- python - uwsgi 错误 - ModuleNotFoundError:没有名为“编码”的模块?