单击按钮上的CakePHP和jQuery Counter

时间:2011-10-19 18:33:05

标签: jquery cakephp

我已经写了一个小jQuery按钮点击计数器,我有点卡住,因为我想提交我的表单添加一行到mysql db(cakephp)然后如果它被添加更新页面上的值,但如果它没有被添加到数据库中,则计数器不会上升。

我坚持如何将值返回给jquery,说它是否成功插入数据库。

这是我目前正在使用的代码。

JS:

$(document).ready(function() 
{
$('.add-vote-link').click( function () 
{
    var img_id = $(this).attr('id');

    $.ajax({  
                type: "POST",  
                url: "/votes/vote/" + img_id,  
            //  data: "img_id="+ img_id,  
                success: function()
        {  
                    //$('form#submit').hide(function(){$('div.success').fadeIn();});   
            $('#vote_counter_'+img_id).html(function(i, val) { return +val+1 });
                }  
    });
});
});

要更新的HTML:

<div id="vote_counter_<?php echo $img['Images']['img_id']; ?>">
    <?php echo $img['Images']['img_vote_count']; ?>
</div>  

php用于将数据提交给数据库,这也可以正常工作,并且对于成功插入返回1,如果没有插入则返回0,如何将其传递回我的jquery函数然后使用if语句不管是否使用计数器。

希望有人可以提供帮助并且iv解释它可以:)

谢谢!

1 个答案:

答案 0 :(得分:0)

如果一切都很完美,你只需要将数据传递为json:D

在页面“/ votes / vote /”+ img_id中你应该把它显示为json数据

视图最像是这样的

<?php
echo $javascript->object($results);
?>

$ results应该是这样的数组

$results = array( 'result' => 1, //any other data you want to pass
);

你的布局应该是这样的

<?php
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, max-age=0, must-revalidate");
header('Content-Type: text/x-json');
echo $content_for_layout;
?>

最后你的$ .ajax应该是这样的

$.ajax({  
            type: "POST",  
            url: "/votes/vote/" + img_id,  
        //  data: "img_id="+ img_id,
            dataType: "json",  
            success: function( data ){  
                if (data.result == 1){
                     counter++;
                } else {
                  //display error message or something
                }
                $('#vote_counter_'+img_id).html(function(i, val) { return +val+1 });
            }  
});

像这样你可以在cakephp页面执行后将任何数据传递给你的jquery,希望这对你有用:D(我是从记忆中做到的,所以也许我错过了一些东西:S)