是否可以在Symfony2中使用jquery更新数据库?

时间:2014-11-04 13:53:52

标签: php jquery symfony doctrine-orm

我已经安装了jsrouting-bundle,这是我的代码:

使用Javascript:

$(document).ready(function () {
    $(".pmcontents").hide();
    $(".pmbox").click(function () {
        $(this).css("font-weight", "normal");
        $(this).next().toggle();
        var myValue = $('this').attr('id');
        var DATA = 'sentValue=' + myValue;
        $.ajax({
            type: "POST",
            url: Routing.generate('isread'),
            data: DATA,
            cache: false,
            success: function (data) {
                alert("database has been updated");

            }
        });
    });

});

控制器:

public function isreadAction() {
    $request = $this->get('request');
    if ($request->isXmlHttpRequest()) {
        var_dump($request->request->get('sentValue'));
        $em = $this->getDoctrine()->getEntityManager();
        $pm = $this->getDoctrine()
                ->getRepository('LoginLoginBundle:Privatemessage')
                ->findBypmid($request->request->get('sentValue'));

        $pm->setIsRead(true);
        $em->flush();
        return new Response();
    }
}

路由:

isread:
    path:   /game/isread
    defaults: { _controller: LoginLoginBundle:Default:isread }
    requirements:
     _method:  POST 

但它不能更新is_read列。我的供应商文件夹也出现错误:

Errors

2 个答案:

答案 0 :(得分:3)

你可以用ajax

来做到这一点
$.ajax({
    type: "POST",
    // Routing.generate = install fosjsroutingbundle
    url: Routing.generate('the_route_of_your_contoller'),
    data: DATA,
    cache: false,
    success: function(data){
           alert("database has been updated");

        }
    });    

控制器将具有持久性/更新角色


路线,与正常情况相同,只需添加要求:

path:   /..
defaults: { _controller: ..:..:.. }
requirements:
     _method:  POST

回复

return new Response();

文件顶部有use Symfony\Component\HttpFoundation\Response;


第二次编辑

我喜欢这样:

jquery:

var myValue = $('this').attr('id');
//in POST ajax
var DATA = 'sentValue=' + myValue;
控制器中的

$request = $this->get('request');
if($request->isXmlHttpRequest())
{
     $value = $request->request->get('sentValue');

答案 1 :(得分:0)

您应该尝试从jquery($ .ajax())调用AJAX,但您需要的是一个请求端点,它将根据请求提供响应,这意味着您必须构建一个PHP / Symfony2 -Script首先通过AJAX调用它:

概念:

User interaction --> jQuery.ajax() --> symfony2_script.php --> jQuery response processing --> view update